下载Reachability并导入 https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
#import "Reachability.h"
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
//开启网络状况的监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)name:kReachabilityChangedNotification object:nil];
_reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[_reachability startNotifier];
self.status = [_reachability currentReachabilityStatus];
return YES;
}
-(void)reachabilityChanged:(NSNotification*)notification{
Reachability*reach = [notificationobject];
if([reachisKindOfClass:[Reachabilityclass]]){
NetworkStatusstatus = [reachcurrentReachabilityStatus];
//如果网络状态发生改变
if(status !=self.status) {
NSString*network = [selfisInternetWith:status] ;
if([networkisEqualToString:@"没网"]) {
NSLog(@"没网 - %@",[selfcurrentViewController] );
[[self currentViewController] presentViewController:[[NoNetWorkViewController alloc]init] animated:YES completion:^{
}];
}
}
}
}
//获取当前控制器
-(UIViewController*)currentViewController
{
UIViewController * currVC = nil;
UIViewController * Rootvc = self.window.rootViewController ;
do{
if([RootvcisKindOfClass:[UINavigationControllerclass]]) {
UINavigationController * nav = (UINavigationController *)Rootvc;
UIViewController * v = [nav.viewControllers lastObject];
currVC = v;
Rootvc = v.presentedViewController;
continue;
}elseif([RootvcisKindOfClass:[UITabBarControllerclass]]){
UITabBarController * tabVC = (UITabBarController *)Rootvc;
currVC = tabVC;
Rootvc = [tabVC.viewControllersobjectAtIndex:tabVC.selectedIndex];
continue;
}elseif([RootvcisKindOfClass:[XCBaseTabBarControllerclass]]){
XCBaseTabBarController * tabVC = (XCBaseTabBarController *)Rootvc;
currVC = tabVC;
Rootvc = tabVC.selectedViewController;
continue;
}
}while(Rootvc!=nil);
returncurrVC;
}
///返回根据status返回当前网络状态
-(NSString*)isInternetWith:(NetworkStatus)status
{
switch(status) {
case NotReachable:
return@"没网";
break;
case ReachableViaWiFi:
return@"WIFI上网";
break;
case ReachableViaWWAN:
return@"移动上网";
break;
default:
break;
}
}