iOS - 监测网络状态

第一种

  • 在控制器初始化的时候,检测是否可以打开百度网页,如果可以打开则data不为空,否则为nil,不需要框架简单暴力.
    NSURL *scriptUrl = [NSURL URLWithString:@"https://www.baidu.com"];
    NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
    if (data)
        NSLog(@"Device is connected to the Internet");
    else
        NSLog(@"Device is not connected to the Internet");

第二种

  • 通过网络检测框架Reachability来检测
  • 只需要下载导入.h与.m文件即可
  • 在需要检测的地方创建方法或者直接写到公共类里面写成类方法也可以.
- (BOOL)connected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return networkStatus != NotReachable;
}
  • 在需要检测的地方调用
    if (![self connected]) {
        // Not connected
        NSLog(@"没连接");
    } else {
        // Connected. Do some Internet stuff
        NSLog(@"有联网");
    }

第三种

  • 相对前面两种比较好的地方就是不需要手动调用检测网络的方法,直接去实时监听网络状态.
  • 所需要的网络框架是tonymillion/Reachability
  • git地址 https://github.com/tonymillion/Reachability
  • 可以在rootViewController中的-(void) viewWillAppear:(BOOL)animated 中创建监听.
-(void) viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachableFoo = [Reachability reachabilityForInternetConnection];
    [internetReachableFoo startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [hostReachable startNotifier];
    // now patiently wait for the notification
}
  • 完成通知方法,可以检测目前的网络是什么状态,是否有网络,wifi,以及wwan
-(void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachableFoo currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");

            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");

            break;
        }
    }

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            break;
        }
    }
}
  • 来自stackoverflow的大神灵感 : http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-ios-or-osx

你可能感兴趣的:(ios,框架使用)