此方法依赖AFNetworking第三方库(✈️)
以下代码写在appDelegate.m调用即可
/**
实时检查当前网络状态
*/
- (void)addReachabilityManager {
AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
// [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(afNetworkStatusChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];//这个可以放在需要侦听的页面
[afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:{
NSLog(@"网络不通:%@",@(status) );
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi:{
NSLog(@"网络通过WIFI连接:%@",@(status));
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN:{
NSLog(@"网络通过无线连接:%@",@(status) );
break;
}
default:
break;
}
NSLog(@"网络状态数字返回:%@",@(status));
NSLog(@"网络状态返回: %@", AFStringFromNetworkReachabilityStatus(status));
NSLog(@"isReachable: %@",@([AFNetworkReachabilityManager sharedManager].isReachable));
NSLog(@"isReachableViaWWAN: %@",@([AFNetworkReachabilityManager sharedManager].isReachableViaWWAN));
NSLog(@"isReachableViaWiFi: %@",@([AFNetworkReachabilityManager sharedManager].isReachableViaWiFi));
}];
[afNetworkReachabilityManager startMonitoring]; //开启网络监视器;
}