标签:
可以使用AFN框架中的AFNetworkReachabilityManager来监听网络状态的改变,也可以利用苹果提供的Reachability来监听。建议在开发中直接使用AFN框架处理。
示例代码如下:
-(void)afn
{
//1.创建网络状态监测管理者
AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
//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;
}
}];
Reachablity 是一个iOS下检测,iOS设备网络环境用的库。
苹果官方提供的Doc,下载地址: http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
-(void)viewDidLoad
{
[super viewDidLoad];
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityStatusChange) name:kReachabilityChangedNotification object:nil];
//创建对象
Reachability *r = [Reachability reachabilityForInternetConnection];
[r startNotifier];
self.r = r;
}
-(void)reachabilityStatusChange
{
if ([Reachability reachabilityForInternetConnection].currentReachabilityStatus == ReachableViaWWAN) {
NSLog(@"3G|4G");
return;
}
if ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == ReachableViaWiFi) {
NSLog(@"wifi");
return;
}
NSLog(@"未知");
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self];
[self.r stopNotifier];
}
标签:
原文地址:http://www.cnblogs.com/liugengqun/p/5140903.html