一、说明
在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的:
(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)
(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验
WIFI\3G网络:自动下载高清图片
低速网络:只下载缩略图
没有网络:只显示离线的缓存数据
苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
二、监测网络状态
Reachability的使用步骤
添加框架SystemConfiguration.framework
添加代码
包含头文件
#import "Reachability.h"
代码示例:
1、判断能否连接网络//判断是否能够上网 -(BOOL)hasNetWork{ //创建一个reachiability对象 //需要一个有效的网址,通过该网址返回一个reachability对象 #if 0 Reachability *reach=[Reachability reachabilityWithHostName:@"www.baidu.com"]; #else //创建一个reachiability对象 Reachability * reach = [Reachability reachabilityForInternetConnection]; #endif //获得当前的网络状态 NetworkStatus status = [reach currentReachabilityStatus]; #if 0 switch (status) { //用于检查是有网络 case NotReachable: NSLog(@"mark:没有网络"); return NO; break; //用于检测是否是WIFI case ReachableViaWiFi: NSLog(@"mark:wifi网络"); return YES; break; //用于检查是否是3G case ReachableViaWWAN:{ NSLog(@"mark:手机网络"); return YES; } break; default: break; } #else if (status == NotReachable) { return NO; } else{ return YES; } #endif } 2、判断当前的网络状态
//当前的网络状态 -(void)currentNetworkStatu{ #if 0 Reachability *reach=[Reachability reachabilityWithHostName:@"www.baidu.com"]; #else Reachability * reach = [Reachability reachabilityForInternetConnection]; #endif switch ([reach currentReachabilityStatus]) { case NotReachable: NSLog(@"mark:not work"); break; case ReachableViaWiFi: NSLog(@"mark:wifi"); break; case ReachableViaWWAN:{ NSLog(@"mark:wan"); } break; default: break; } } 3、监听网络状态
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ///开启网络状况的监听 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; #if 0 //需要一个有效的网址,通过该网址返回一个reachability对象 //通过这种方法得到的的reachability对象 会自动调用一次reachabilityChanged:这个方法 self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"]; #else //创建一个reachability对象 //通过这中方法得到的reachability,只有在网络状态发生改变时才会调用:reachabilityChanged方法。 self.reach = [Reachability reachabilityForInternetConnection]; #endif //开始监听,会启动一个run loop [self.reach startNotifier]; return YES; } //网络状态改变后会调用这个方法 -(void)reachabilityChanged:(NSNotification*)notification { //拿到reachability对象 Reachability * reach = [notification object]; //NSParameterAssert([reach isKindOfClass: [Reachability class]]); //拿到当前网络的状态 NetworkStatus status = [reach currentReachabilityStatus]; if (status == NotReachable) { NSLog(@"Notification Says Unreachable"); } else if(status == ReachableViaWWAN){ NSLog(@"Notification Says mobilenet"); } else if(status == ReachableViaWiFi){ NSLog(@"Notification Says wifinet"); } } - (void)dealloc { //停止监听 [self.reach stopNotifier]; // 删除通知对象 [[NSNotificationCenter defaultCenter] removeObserver:self]; } 参考资料: iOS开发网络篇—监测网络状态
