一般有两种方式,都是第三方的框架,*嘛,能用就先用着,后面再优化。
一:Reachability
1.首先在AppDelegate.h添加头文件"Reachability.h",导入框架SystemConfiguration.frame。
2. 在AppDelegate.m中这样实现:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//开启网络状况的监听
//来订阅实时的网络状态变化通知。导入Reachability.h头文件,然后注册一个对象来订阅网络状态变化的信息,网络状态变化的信息名称为kReachabilityChanged-Notification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//通过检查某个主机能否访问来判断当前网络是否可用:
self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ; //开始监听,会启动一个run loop
[self.hostReach startNotifier]; } -(void)reachabilityChanged:(NSNotification *)note{
Reachability *currReach = [note object]; NSParameterAssert([currReach isKindOfClass:[Reachability class]]); //对连接改变做出响应处理动作 NetworkStatus status = [currReach currentReachabilityStatus]; //如果没有连接到网络就弹出提醒实况 self.isReachable = YES; if(status == NotReachable){ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
[alert release];
self.isReachable = NO;
return; } if (status==kReachableViaWiFi||status==kReachableViaWWAN) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接信息" message:@"网络连接正常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; // [alert show]; [alert release];
self.isReachable = YES; }
} 然后在每个页面的viewWillAppear:加上: -(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(appDlg.isReachable){
NSLog(@"网络已连接");//执行网络正常时的代码
}
else{
NSLog(@"网络连接异常");//执行网络异常时的代码
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
这样就可以检查到在运行程序时网络突然的中断和连接。Reachability类实际上是苹果公司对SCNetworkReachability API的封装,这个API定义在SystemConfigure.framework库中。如果有其他特别的需求,也可以直接使用这个原生的SCNetworkReachability类。
二:AFNetworking监测
1.导入框架,和头文件#import <AFNetworkReachabilityManager.h>
2.代码:
-(void)afn{
//1.创建网络状态监测管理者
AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
//开启监听,记得开启,不然不走block
[manger startMonitoring];
//2.监听改变
[manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
/*
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,
*/
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"没有网络");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G|4G");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WiFi");
break;
default:
break;
}
}];
}