一:苹果官方提供的Reachability示例程序的监测
导入Reachability.h和Reachability.m文件
/**监控网络*/
@property(nonatomic,strong)Reachability*reachability;
//监听通知
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(getNetworkStatus)name:kReachabilityChangedNotificationobject:nil];
//开始监控网络
self.reachability= [ReachabilityreachabilityForInternetConnection];
[self.reachability startNotifier];
//�只要网络状态改变,就会调用�这个方法查看当前的网络
- (void)getNetworkStatus
{
if([ReachabilityreachabilityForLocalWiFi].currentReachabilityStatus!=NotReachable) {
NSLog(@"wifi");
}elseif([ReachabilityreachabilityForInternetConnection].currentReachabilityStatus!=NotReachable) {
NSLog(@"蜂窝网络");
}else{
NSLog(@"无网络连接");
}
}
需要注意在结束监听时要移除网络监测的通知:
- (void)dealloc
{
[[NSNotificationCenterdefaultCenter]removeObserver:self];
[self.reachability stopNotifier];
self.reachability=nil;
}
二:AFNetworking中的网络状态监测
导入AFNetworking框架...
//开始网络监控
AFNetworkReachabilityManager*mgr = [AFNetworkReachabilityManager sharedManager];
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//在block中拿到当前网络状态
NSLog(@"-----当前的网络状态---%zd", status);
}];
[mgr startMonitoring];
status的值�与网络状态的对应如下:
//当前无网络
AFNetworkReachabilityStatusNotReachable=0,
//蜂窝网络
AFNetworkReachabilityStatusReachableViaWWAN =1,
//wifi
AFNetworkReachabilityStatusReachableViaWiFi =2,