开源第三方地址: https://github.com/tonymillion/Reachability
当前使用网络检测
Reachability *reachable = [Reachability reachabilityForInternetConnection];
if ([reachable currentReachabilityStatus] == ReachableViaWiFi) {
NSLog(@"wifi - 已连接");
} else if ([reachable currentReachabilityStatus] == ReachableViaWWAN) {
NSLog(@"数据 - 已连接");
} else {
NSLog(@"无网络连接");
}
当前网络变化监听
// 添加 监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChange:) name:kReachabilityChangedNotification object:nil];
self.reach = [Reachability reachabilityForInternetConnection];
[self.reach startNotifier];
- (void)netChange:(NSNotification *)notification{
if ([self.reach currentReachabilityStatus] == ReachableViaWiFi) {
NSLog(@"wifi");
} else if ([self.reach currentReachabilityStatus] == ReachableViaWWAN) {
NSLog(@"数据");
} else {
NSLog(@"无网络");
}
}
// 注意 需要remove 监听
[self.reach stopNotifier];
使用 block 多线程监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChange) name:kReachabilityChangedNotification object:nil];
self.reach = [Reachability reachabilityForInternetConnection];
[self.reach startNotifier];
- (void)netChange{
self.reach.reachableBlock = ^(Reachability *reachable) {
dispatch_async(dispatch_get_main_queue(), ^{
// UI
NSLog(@"当前网络已连接");
NSLog(@"当前状态-%@",[reachable currentReachabilityString]);
});
};
self.reach.unreachableBlock = ^(Reachability *reachable) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"当前无网络连接");
NSLog(@"当前状态-%@",[reachable currentReachabilityString]);
});
};
// 这个比较悬,应该是跟本地wifi存在可以连接联网
self.reach.reachabilityBlock = ^(Reachability *reachable, SCNetworkConnectionFlags flags) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"有网络可用");
NSLog(@"当前状态-%@",[reachable currentReachabilityString]);
});
};
}
// 注意 需要remove 监听
[self.reach stopNotifier];
其他
。