1.创建监听管理者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
2.打开检测开始检测网络状态
[manager startMonitoring];
3.监听网络状态的改变
AFNetworking 中四个状态的枚举值如下:
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1, //未知
AFNetworkReachabilityStatusNotReachable = 0, //无连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, //3G
AFNetworkReachabilityStatusReachableViaWiFi = 2, //WIFI
};
{ switch (status)
{
case
AFNetworkReachabilityStatusUnknown:
{ //未知网络 NSLog( @"未知网络");
} break;
case
AFNetworkReachabilityStatusNotReachable:
{ //无法联网 NSLog( @"无法联网");
} break;
case AFNetworkReachabilityStatusReachableViaWWAN:
{ //手机自带网络 NSLog( @"当前使用的是2g/3g/4g网络");
} break;
case AFNetworkReachabilityStatusReachableViaWiFi:
{ //WIFI NSLog( @"当前在WIFI网络下");
} }
}];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
{
//未知网络
NSLog(@"未知网络");
}
break;
case AFNetworkReachabilityStatusNotReachable:
{
//无法联网
NSLog(@"无法联网");
}
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
{
//手机自带网络
NSLog(@"当前使用的是2g/3g/4g网络");
}
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
{
//WIFI
NSLog(@"当前在WIFI网络下");
}
}
}];
example:
AFNetworkReachabilityManager * mgr = [AFNetworkReachabilityManager sharedManager];
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 当网络状态发生改变的时候调用这个block
switch (status) {
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WIFI");
[[NSUserDefaults standardUserDefaults] setObject:@"wifi" forKey:@"network"];
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"自带网络");
[[NSUserDefaults standardUserDefaults] setObject:@"3g" forKey:@"network"];
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"没有网络");
[[NSUserDefaults standardUserDefaults] setObject:@"without" forKey:@"network"];
break;
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知网络!");
[[NSUserDefaults standardUserDefaults] setObject:@"unknown" forKey:@"network"];
break;
default:
break;
} }];
// 开始监控
[mgr startMonitoring];