推荐使用一个类库RealReachability,复制名字到github就能找到。
使用RealReachability的好处:
1.现在很流行的公用wifi,需要网页鉴权,鉴权之前无法上网,但本地连接已经建立;
2.存在了本地网络连接,但信号很差,实际无法连接到服务器;
3.iOS连接的路由设备本身没有连接外网。
使用前要先开启网络检测:
[GLobalRealReachability startNotifier];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkChange:) name:kRealReachabilityChangedNotification object:nil];
实现网络变化全局监听:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GLobalRealReachability startNotifier];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkChange:) name:kRealReachabilityChangedNotification object:nil];
return YES;
}
- (void)netWorkChange:(NSNotification *)notification{
MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithWindow:self.window];
HUD.mode = MBProgressHUDModeText;
[self.window addSubview:HUD];
HUD.removeFromSuperViewOnHide = YES;
[HUD show:YES];
[HUD hide:YES afterDelay:1.5f];
RealReachability *reachability = (RealReachability *)notification.object;
ReachabilityStatus status = [reachability currentReachabilityStatus];
switch (status) {
case RealStatusNotReachable:
{
HUD.labelText = @"无网络";
}
break;
case RealStatusViaWiFi:
{
HUD.labelText = @"WIFI";
}
break;
case RealStatusViaWWAN:
{
HUD.labelText = @"3G";
}
break;
default:
break;
}
}
实现手动监听
- (void)doButtonAction{
MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
HUD.mode = MBProgressHUDModeText;
[self.view addSubview:HUD];
HUD.removeFromSuperViewOnHide = YES;
[HUD show:YES];
[HUD hide:YES afterDelay:1.5f];
[GLobalRealReachability reachabilityWithBlock:^(ReachabilityStatus status) {
switch (status) {
case RealStatusNotReachable:
{
HUD.labelText = @"无网络";
}
break;
case RealStatusViaWiFi:
{
HUD.labelText = @"WIFI";
}
break;
case RealStatusViaWWAN:
{
HUD.labelText = @"3G";
}
break;
default:
break;
}
}];
}
网友评论