方法一:利用系统状态栏判断网络状态
// 状态栏是由当前app控制的,首先获取当前app
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
int type = 0;
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
}
}
switch (type) {
case 1:
return @"2G";
break;
case 2:
return @"3G";
case 3:
return @"4G";
case 5:
return @"WIFI";
default:
return @“NO-WIFI";//代表未知网络
break;
}
当然,此方法存在一定的局限性,比如当状态栏被隐藏的时候,无法使用此方法。
方法二:使用第三方库AFNetWorking判断(使用前记得导入 #import "AFNetworking.h")
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case -1:
NSLog(@"未知网络");
break;
case 0:
NSLog(@"网络不可达");
break;
case 1:
NSLog(@"GPRS网络");
break;
case 2:
NSLog(@"wifi网络");
break;
default:
break;
}
if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
{
NSLog(@"有网");
}else
{
NSLog(@"没有网");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络失去连接" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
alert.delegate = self;
[alert show];
}
}];