对于一些需要与服务器进行长连接的App,需要对网络状态进行监控,当网络不佳时及时提醒用户,从而提高用户体验。通过苹果自带的框架和Reachability类可以实现网络状态改变的监听。
要实现网络监听,按照下面的步骤进行。
①导入SystemConfiguration框架。
②通过Xcode的帮助文档搜索Reachability,打开样例工程,将其中的Reachability类的代码拷贝到自己的工程,有两个文件,如下图所示。
③创建对象,保存对象,添加监听和启动监听。
注意reachabilityForInternetConnection才能用于wifi、3G、无网络三种状态。
注意监听的名称为kReachabilityChangedNotification。
- (void)viewDidLoad{
[super viewDidLoad];
Reachability *wifiReach = [Reachability reachabilityForInternetConnection];
_wifiReach = wifiReach;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange:) name:kReachabilityChangedNotification object:nil];
[wifiReach startNotifier];
}④在监听的回调中拿到状态判断。
注意要实现三种网络状态,要用真机来调试。
- (void)networkStateChange:(NSNotification *)nof{
switch (self.wifiReach.currentReachabilityStatus) {
case ReachableViaWiFi:
NSLog(@"wifi");
break;
case ReachableViaWWAN:
NSLog(@"移动数据");
break;
case NotReachable:
NSLog(@"无网络");
break;
}
}⑤在控制器销毁时,一定要记得移除监听。- (void)dealloc{
[self.wifiReach stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}