我监听网络状况用的是AFNetNetWorking,你可以用其他的方法,原理都一样;我所有的控制器都继承于基类控制器;
1.监听网络
<span style="font-size:18px;">#pragma mark - 监测网络状态
- (void)monitorNetworkState{
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager startMonitoring];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"没有网络");
PersonInfo.hasNet = NO;
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:KLoadDataBase object:nil userInfo:@{@"netType":@"NotReachable"}]];
break;
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知");
if(!PersonInfo.hasNet){
[YJYYStatusHUD hildErrorMessage];
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:KLoadDataBase object:nil userInfo:@{@"netType":@"Unknown"}]];
}
PersonInfo.hasNet = YES;
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WiFi");
if(!PersonInfo.hasNet){
[YJYYStatusHUD hildErrorMessage];
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:KLoadDataBase object:nil userInfo:@{@"netType":@"WiFi"}]];
}
PersonInfo.hasNet = YES;
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G|4G");
if(!PersonInfo.hasNet){
[YJYYStatusHUD hildErrorMessage];
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:KLoadDataBase object:nil userInfo:@{@"netType":@"WWAN"}]];
}
PersonInfo.hasNet = YES;
break;
default:
break;
}
}];
}</span>
每次网络发生改变我都发出通知;PersonInfo.hasNet是存放网络变化的值;我放在工程单利里面;
2.在基类里面接收广播:BaseViewController
我之所以把这个方法写在基类里面
- (void)getLoadDataBase:(NSNotification *)text;
是因为每个页面我都要用到;然后在其他页面只需要调用父类的方法即可;
//网络监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLoadDataBase:) name:KLoadDataBase object:nil];
- (void)getLoadDataBase:(NSNotification *)text{
NSLog(@"开始重新加载网络");
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter ]removeObserver:self name:KLoadDataBase object:nil];
}
3.选择在某个页面刷新数据;
比如首页数据;_isLoadHead表示这个页面是否加载过,如果加载过表示页面有数据,不需要自动刷新,如果一进来是断网状态这是没有数据的,然后在有网的时候,会自动加载刷新数据;
- (void)getLoadDataBase:(NSNotification *)text{
[super getLoadDataBase:text];
if(!_isLoadHead){
[self getAllClassDataBase];
}
}
[self getAllClassDataBase];为加载数据的方法
比如有的页面我想要最新数据,那就简单一点,直接刷新就好了;
#pragma mark - 有网络后加载数据
- (void)getLoadDataBase:(NSNotification *)text{
[super getLoadDataBase:text];
[self.tableview.mj_header beginRefreshing];
}