使用Reachability类检测网络状态

首先去
https://developer.apple.com/library/ios/samplecode/Reachability/Listings/Reachability_Reachability_m.html 下载Reachability类。

然后将Reachability.h和Reachability.m拖进你的工程,然后添加SystemConfiguration.framework框架。
注:Reachability 2.x版本是不支持ARC的,如果你用的是2.x的版本,请手动禁用该类的ARC。TARGETS->Build Phases->Compile Sources双击Reachability.m,输入框添加“-fno-objc-arc”。

然后判断网络状态方法如下:

    NSString *site = @"www.MyWeb.com";
    Reachability *reach = [Reachability reachabilityWithHostName:site];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"不能访问%@", site);
            break;
        case ReachableViaWiFi:
            NSLog(@"使用wifi访问%@", site);
            break;
        case ReachableViaWWAN:
            NSLog(@"使用3G/4G访问%@", site);
            break;
        default:
            break;
    }

判断有无网络连接:

    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable) {
        [self showAlert:@"网络可用"];
    } else {
        [self showAlert:@"网络不可用"];
    }

监听网络状态的方法,写在AppDelegate类的application: didFinishLaunchingWithOptions:里面:
注册通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[reachability startNotifier];

网络状态变化实现

/**
 *此函数通过判断联网方式,通知给用户
 */
- (void)reachabilityChanged:(NSNotification *)notification {
    Reachability *curReachability = [notification object];
    NSParameterAssert([curReachability isKindOfClass:[Reachability class]]);
    NetworkStatus curStatus = [curReachability currentReachabilityStatus];
    switch (curStatus) {
        case NotReachable:
            NSLog(@"无网络");
            break;
        case ReachableViaWiFi:
            NSLog(@"使用wifi网络");
            break;
        case ReachableViaWWAN:
            NSLog(@"使用3G/4G网络");
            break;
            
        default:
            break;
    }
}

最后新版本中reachabilityForLocalWiFi方法被移除了


Paste_Image.png

你可能感兴趣的:(使用Reachability类检测网络状态)