网络监听用到的类为Reachability.h,这个Xcode项目里面是不自带的,需要从github上面下载,在使用的时候记着导入SystemConfiguration.framework。
首先是在AppDelegate.m中设置网络监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
初始化:
_reachability = [Reachability reachabilityForInternetConnection]; [_reachability startNotifier]; [self updateInterfaceWithReachability:_reachability];
实现两个方法:
– (void) reachabilityChanged: (NSNotification* )note;//网络连接改变
– (void) updateInterfaceWithReachability: (Reachability*) curReach;//处理连接改变后的情况
下面是方法的具体实现,可根据情况自行改变:
// 连接改变 - (void) reachabilityChanged: (NSNotification* )note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); [self updateInterfaceWithReachability: curReach]; } //处理连接改变后的情况 - (void) updateInterfaceWithReachability: (Reachability*) curReach { //对连接改变做出响应的处理动作。 NetworkStatus status = [curReach currentReachabilityStatus]; if (status == NotReachable) { _isReachable = NO; //没有连接到网络就弹出提实况 UIAlertView *netAlert = [[UIAlertView alloc] initWithTitle:@"蜂窝移动数据已关闭" message:@"启用蜂窝移动数据或无线局域网来访问数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [netAlert show]; } else { _isReachable = YES; } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/3291.html