iOS网络监测,监测单个页面写在ViewController里,监测全部写在AppDelegate中,而且不用终止
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//根据主机名判断网络是否连接
self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
//注册网络监听通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kReachabilityChanged) name:kReachabilityChangedNotification object:nil];
//开启监听
[self.reach startNotifier];
}
-(void)kReachabilityChanged{
switch (self.reach.currentReachabilityStatus) {
case NotReachable:
NSLog(@"没有网");
break;
case ReachableViaWiFi:
NSLog(@"wifi");
break;
case ReachableViaWWAN:
NSLog(@"移动蜂窝网");
break;
default:
NSLog(@"未知网络");
break;
}
}
-(void)dealloc{
//把当前的对象所有通知删除
[[NSNotificationCenter defaultCenter] removeObserver:self];
//停止监听
[self.reach stopNotifier];
}