苹果官方网络连接类型监测代码包
打开项目压缩文件,把Reachability.h 和 Reachability.m加入到自己的项目中。
self.reachability = [Reachability reachabilityWithHostName:@"https://www.baidu.com/"];
switch ([self.reachability currentReachabilityStatus]) {
case NotReachable:
NSLog(@"当前网络不可用");
break;
case ReachableViaWiFi:
NSLog(@"当前网络为WiFi");
break;
case ReachableViaWWAN:
NSLog(@"当前网络为移动网络");
break;
default:
break;
}
//如需动态监视网络变化,只需添加通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netChange:) name:kReachabilityChangedNotification object:nil];
[self.reachability startNotifier];
- (void)netChange:(NSNotification *)notification{
Reachability *reachability = [Reachability reachabilityWithHostName:@"https://www.baidu.com/"];
switch ([reachability currentReachabilityStatus]) {
case NotReachable:
NSLog(@"当前网络不可用");
break;
case ReachableViaWiFi:
NSLog(@"当前网络为WiFi");
break;
case ReachableViaWWAN:
NSLog(@"当前网络为移动网络");
break;
default:
break;
}
}
在合适的时机要注销掉网络监测和通知。
[self.reachability stopNotifier];
[[NSNotificationCenter defaultCenter]removeObserver:self name:kReachabilityChangedNotification object:nil];