IOS监听网络状态&以及方法冲突解决
首先,项目要在App打开时监听网络状态,Wi-Fi和运营商有网络时开启MQTT连接。利用AFN实现网络状态监听。
1、在AppDelegate.m中引入#import "AFNetworking.h"
枚举网络状态
typedef enum : NSUInteger {
unknown,
notConnect,
wwan,
wifi,
} Networkstatus;
开启网络监听
[self networkMonitoring];//开启网络监听
#pragma mark - NetworkMonitoring
-(void)networkMonitoring{
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager startMonitoring];//开启监听
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
self.networkstatus = unknown;
NSLog(@"当前网络未知");
break;
case AFNetworkReachabilityStatusNotReachable:
self.networkstatus = notConnect;
NSLog(@"当前无网络连接");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
self.networkstatus = wifi;
//连接 mqtt服务器
[self connnetMQTTServer];
NSLog(@"当前使用无线网络");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
self.networkstatus = wwan;
//连接 mqtt服务器
[self connnetMQTTServer];
NSLog(@"当前使用运营商网络");
break;
default:
break;
}
}];
}
到这为止已经可以监听网络方法,但是因为监听是耗时操作,如果在首页viewController中同样写这个方法当返回时只走一个viewController,在Appdelegete的方法不会 执行
因此,在别的页面用通知监听状态改变
//-(void)viewDidLoad 中
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AFNNetWorkStatusChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
- (void)AFNNetWorkStatusChanged:(NSNotification *)notice{
NSDictionary *dic = notice.userInfo; //获取网络状态
NSInteger status = [[dic objectForKey:@"AFNetworkingReachabilityNotificationStatusItem"] integerValue];
if(status == AFNetworkReachabilityStatusNotReachable) {
//无网络连接
[self.locService stopUserLocationService];//停止定位
UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"当前暂无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
[alertV show];
}else if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) { }else{
}
}
—— end ——