1.首先下载苹果官方监听的代码:
苹果官方监听demo
2.把demo中的 Reachability.h 和 Reachability.m 文件导入到工程
3.把头文件Reachability.h 导入BaseController.m
4.在baseController.h里面声明一个BOOL值
@property (nonatomic,assign) BOOL isNetWorkingUse;
5.在BaseController.m文件声明
@property (nonatomic,strong) Reachability *reach;
6.在BaseController.m文件代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
/**监听网络变化*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
// 让Reachability对象开启被监听状态
[self.reach startNotifier];
}
/*!
* Called by Reachability whenever status changes.
*/
- (void) reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(Reachability *)reachability {
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus){
case NotReachable: {
self.isNetWorkingUse = NO;
break;
}
case ReachableViaWWAN: {
self.isNetWorkingUse = YES;
break;
}
case ReachableViaWiFi: {
self.isNetWorkingUse = YES;
break;
}
}
}
//注意要销毁通知
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}
网友评论