我们在开发APP时,涉及网络连接的时候,都会想着提前判断一下当前的网络连接状态,如果没有网络,就不再请求url,省去不必要的步骤,所以,这个如何判断?
记得在工程添加:SystemConfiguration.framework
去苹果API里搜索Reachability,下载Demo(点击左上角Download Sample Code 即可下载),把demo里的Reachability.h和Reachability.m拖到自己的工程里。也可以在百度里面搜索”Reachability”,然后下载,不一定非要到苹果官网去下载。
但是使用Reachability有一个问题,就是它只能判断当前是Wifi或者手机自带网络,没有办法详细得判断2G、3G、4G。
如果确定为手机自带网络,这时可以使用系统自带的API来判断是2G、3G还是4G,这就要使用到CTTelephonyNetworkInfo这类,记得在工程添加CoreTelephony.framework
1.引入头文件
//网络
#import "Reachability.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
2.代码:
- (NSString *)getNetconnType{
NSString *netconnType = @"";
Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
switch ([reach currentReachabilityStatus]) {
case NotReachable:// 没有网络
{
netconnType = @"no network";
}
break;
case ReachableViaWiFi:// Wifi
{
netconnType = @"Wifi";
}
break;
case ReachableViaWWAN:// 手机自带网络
{
// 获取手机网络类型
CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
NSString *currentStatus = info.currentRadioAccessTechnology;
if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
netconnType = @"GPRS";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
netconnType = @"2.75G EDGE";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
netconnType = @"3G";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
netconnType = @"3.5G HSDPA";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
netconnType = @"3.5G HSUPA";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
netconnType = @"2G";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
netconnType = @"3G";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
netconnType = @"3G";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
netconnType = @"3G";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
netconnType = @"HRPD";
}else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
netconnType = @"4G";
}
}
break;
default:
break;
}
return netconnType;
}