IOS开发过程中网络状态的监测
(1) 苹果自带的Reachability
注意:Build Phases 中的 Compile Sources中Reachability.m设置
核心代码:
@property (nonatomic, strong) Reachability *reach;
- (void)viewDidLoad {
[super viewDidLoad];
//发送状态改变的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStatusChanged) name:kReachabilityChangedNotification object:nil];
//获取Reachability对象
_reach = [Reachability reachabilityForInternetConnection];
//开始监听网络
[self.reach startNotifier];
}
- (void)dealloc{
[self.reach stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self checkNetworkState];
}
- (void)networkStatusChanged{
NSLog(@"网络状态改变");
[self checkNetworkState];
}
/** 监听网络改变 */
- (void)checkNetworkState{
if ([self isWifi]){
NSLog(@"WIFI");
}else if([self isWan]){
NSLog(@"WAN");
}else{
NSLog(@"无网络连接");
}
}
/** 判断是否为wifi */
- (BOOL)isWifi{
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
//获取当前的状态
NetworkStatus wifiStatus = wifi.currentReachabilityStatus;
if (wifiStatus != NotReachable) {
return YES;
}else{
return NO;
}
}
/** 判断是否为WAN */
- (BOOL)isWan{
Reachability *wan = [Reachability reachabilityForInternetConnection];
NetworkStatus wanStatus = wan.currentReachabilityStatus;
if (wanStatus != NotReachable) {
return YES;
}else{
return NO;
}
}
2 用 AFNetworking 框架中的 AFNetworkReachabilityManager 实现网络状态监听:
@property (nonatomic, strong) AFNetworkReachabilityManager *mgr;
- (void)afnStatus{
self.mgr = [AFNetworkReachabilityManager manager];
[self.mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知原因");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"无网络连接");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WIFI");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"WAN");
break;
default:
break;
}
}];
[self.mgr startMonitoring];
}
- (void)dealloc{
[self.mgr stopMonitoring];
}