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];
}