NetworkReachability相关的API
1. 构造struct sockaddr_in
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
2. 构造SCNetworkReachabilityRef
SCNetworkReachabilityRef networkReachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
SCNetworkReachabilityRef networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
3.构造SCNetworkReachabilityContext
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
4.设置回调SCNetworkReachabilitySetCallback
SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context);
5.将SCNetworkReachabilityRef加入到runloop中
SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
6.主动获取当前的网络状态
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef
之前使用过其他的Reachability第三方库,存在一些问题:
- 没有提供主动获取当前网络状态的方法,进入程序后无法判断当前网络状态,在无网情况下无法弹出网络不可用的提示
- 回调返回的状态前后两次可能是同样的,直接导致断网之后会不停的弹出网络不可用的提示
问题讨论
1. 以前测试网络不可达时会提供一个domain,按照构造SCNetworkReachabilityRef的方法可以使用SCNetworkReachabilityCreateWithAddress
- 提供domain可以确定对特定domain网络状态的反馈,而提供一个空的sockaddr_in,网络的Reachability是如何判断的
- 测试网络Reachability的底层原理是什么
先挖坑,再努力填!