IOS-利用AFNetworking监听网络状态

时间:2021-05-31 15:20:03

步骤

  • 1.创建网络监听者管理者对象
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
  • 2.设置监听 
    • 网络状态
    //显然是枚举值
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,//未识别的网络
AFNetworkReachabilityStatusNotReachable = 0,//不可达的网络
AFNetworkReachabilityStatusReachableViaWWAN = 1,//2G,3G,4G...
AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi网络

-设置网络监听

[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未识别的网络");
break;

case AFNetworkReachabilityStatusNotReachable:
NSLog(@"不可达的网络(未连接)");
break;

case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"2G,3G,4G...的网络");
break;

case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi的网络");
break;
default:
break;
}
}];
  • 3.开始监听
[manager startMonitoring];

代码

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//创建网络监听管理者对象
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];

/*
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,//未识别的网络
AFNetworkReachabilityStatusNotReachable = 0,//不可达的网络(未连接)
AFNetworkReachabilityStatusReachableViaWWAN = 1,//2G,3G,4G...
AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi网络
};
*/

//设置监听
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未识别的网络");
break;

case AFNetworkReachabilityStatusNotReachable:
NSLog(@"不可达的网络(未连接)");
break;

case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"2G,3G,4G...的网络");
break;

case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"wifi的网络");
break;
default:
break;
}
}];
//开始监听
[manager startMonitoring];
}