首先是在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;
- }
- }
来源: http://www.phpxs.com/code/1005449/