首先去
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”。
然后判断网络状态方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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; }
|
判断有无网络连接:
1 2 3 4 5
| if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable) { [self showAlert:@"网络可用"]; } else { [self showAlert:@"网络不可用"]; }
|
监听网络状态的方法,写在AppDelegate类的application: didFinishLaunchingWithOptions:里面:
注册通知
1 2 3
| [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"]; [reachability startNotifier];
|
网络状态变化实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
- (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方法被移除了