检查网络状态:(是否连网)
引入Reachability类
• 通过https://github.com/AtharvaVaidya/AVReachability链接下载Reachability.zip压缩包
• 为项⺫添加SystemConfiguration.framework框架注册网络监听
- 开始监听
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 注册监听者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkState:) name:kReachabilityChangedNotification object:nil];
// 定义成实例变量
_reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
// 开始监听
[_reach startNotifier];
return YES;
}
- (void)networkState:(NSNotification *)notifi{
Reachability *reach = [notifi object];
if (reach.isReachable) {
[[[Toast shareToast] text:@"网络正常" andTime:2] show];
}else {
[[[Toast shareToast] text:@"网络断开" andTime:2] show];
}
}
检查网络状态(WiFi,蜂窝数据)
// 创建访问指定的站点
Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
/*
网络状态
NotReachable = kNotReachable,
ReachableViaWiFi = kReachableViaWiFi,
ReachableViaWWAN = kReachableViaWWAN
*/
// 判断设备的网络状态
if (reach.currentReachabilityStatus == NotReachable) {
NSLog(@"无法连接网络");
}
if (reach.currentReachabilityStatus == ReachableViaWiFi) {
NSLog(@"WiFi状态");
}
if (reach.currentReachabilityStatus == ReachableViaWWAN) {
NSLog(@"3G/4G状态");
}