方法一(官方):
Reachability
================================================================================
框架地址:https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
使用方法
1> 添加一个联网状态监听对象
@property (nonatomic, strong) Reachability *reach;
2> 实例化监听对象
self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
3> 判断联网状态
- (void)netwrokStatusChanged {
switch (self.reach.currentReachabilityStatus) {
case NotReachable:
SJLog(@"没有联网");
break;
case ReachableViaWiFi:
SJLog(@"通过Wi-Fi上网");
break;
case ReachableViaWWAN:
SJLog(@"通过3G上网");
break;
default:
break;
}
}
4> 利用通知中心实时监听联网状态
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(netwrokStatusChanged) name:kReachabilityChangedNotification object:nil];
[self.reach startNotifier];
- (void)dealloc {
// 注册指定的通知监听
[[NSNotificationCenter defaultCenter] removeObserver:selfname:kReachabilityChangedNotification object:nil];
}
// 获得网络监控的管理者
AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
// 设置网络状态改变后的处理
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown: // 未知网络
SJLog(@"未知网络");
break;
case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
SJLog(@"未检到网络");
break;
case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
SJLog(@"通过3G上网");
break;
case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
SJLog(@"通过Wi-Fi上网");
break;
}
}];
// 开始监控
[mgr startMonitoring];