AFNetworkReachabilityManager
监控网络环境变化
写个笔记,省的忘了,有错的地方还请过路大神指出
先说用法:
方法一:
AFNetworkReachabilityManager *reachManager = [AFNetworkReachabilityManager sharedManager];
[reachManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
switch(status) {
case-1:
NSLog(@"未知");
break;
case0:
NSLog(@"未连接");
break;
case1:
NSLog(@"蜂窝");
break;
case2:
NSLog(@"wifi");
break;
default:
break;
}
}];
[reachManager startMonitoring];
方法二:别忘了注销通知
[[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(printNetworkStatus:) name: AFNetworkingReachabilityDidChangeNotification object: nil];
-(void)printNetworkStatus:(NSNotification *)notification
{
switch([notification.userInfo[AFNetworkingReachabilityNotificationStatusItem] integerValue]) {
case-1:
NSLog(@"未知");
break;
case0:
NSLog(@"未连接");
break;
case1:
NSLog(@"蜂窝");
break;
case2:
NSLog(@"wifi");
break;
default:
break;
}
}
核心:
1、AFNetworkReachabilityStatus (网络状态枚举)
2、SCNetworkReachabilityRef (网络连接判断)iOS api
3、- (void)startMonitoring; //开始监控
1、AFNetworkReachabilityStatus:
typedef NS_ENUM(NSInteger,**AFNetworkReachabilityStatus**) {
AFNetworkReachabilityStatusUnknown = -1,//未知状态
AFNetworkReachabilityStatusNotReachable = 0,//无网络状态
AFNetworkReachabilityStatusReachableViaWWAN = 1,//蜂窝状态
AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi状态
};
@property(readwrite,nonatomic,assign)AFNetworkReachabilityStatus **networkReachabilityStatus**;
2、SCNetworkReachabilityRef:
官方解释:这是处理网络的地址或名称
** 5个初始化:SCNetworkReachabilityRef的体现**
- (instancetype) initWithReachability: (SCNetworkReachabilityRef) reachability;
+ (instancetype) managerForAddress: (const void *) address; //监听指定socket地址的网络状态
+ (instancetype) manager;
+(instancetype) sharedManager; //单例
以上这4个初始化方法从上往下为被包含关系,具体如图:
+(instancetype) managerForDomain:(NSString *)domain;
监听指定domain的网络状态,包含 initWithReachability 方法,与 managerForAddress 同级
3、- (void)startMonitoring;//开始监控:
首先要去看 interface 里声明的3个对象:前两个是之前所说的核心
@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
主要分为5步:和以上3个对象息息相关
//停止监控
[self stopMonitoring];
//创建上下文
SCNetworkReachabilityContext context = { , , , , };
//设置Callback
SCNetworkReachabilitySetCallback( , , );
//加入到主RunLoop,保持监听
SCNetworkReachabilityScheduleWithRunLoop( , , );
//在global线程回调Callback,回到主线程发送当前状态
dispatch_async(dispatch_get_global_queue(), ^{ });
总结:
AFNetworkReachabilityManager 这个类就是通过 某个套路 给 networkReachabilityStatus 对象赋值,使用它就是为了获取 networkReachabilityStatus 的值。
某个套路:
AFNetworkReachabilityManager 初始化时把 networkReachabilityStatus 赋值为 AFNetworkReachabilityStatusUnknown ,
在 startMonitoring 方法中塞到 block 里赋值,再塞到苹果 api 中回调。
网友评论