标签:
直接贴代码吧,ios7之后是获取的较为准确,7以下我拿iphone5测试的是无法区分3g/2g。连iphone4都能升到7.1.4,而且目前主流的设备7以下的系统已经很少了,这个方案尽管不太完美,但影响不会太大
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
string GetNetWorkType()
{
string strNetworkType = "";
//创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
struct sockaddr_storage zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.ss_len = sizeof(zeroAddress);
zeroAddress.ss_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
//获得连接的标志
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
//如果不能获取连接标志,则不能连接网络,直接返回
if (!didRetrieveFlags)
{
return strNetworkType;
}
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// if target host is reachable and no connection is required
// then we‘ll assume (for now) that your on Wi-Fi
strNetworkType = "WIFI";
}
if (
((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
)
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
strNetworkType = "WIFI";
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init];
NSString *currentRadioAccessTechnology = info.currentRadioAccessTechnology;
if (currentRadioAccessTechnology)
{
if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE])
{
strNetworkType = "4G";
}
else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS])
{
strNetworkType = "2G";
}
else
{
strNetworkType = "3G";
}
}
}
else
{
if((flags & kSCNetworkReachabilityFlagsReachable) == kSCNetworkReachabilityFlagsReachable)
{
if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection)
{
if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired)
{
strNetworkType = "2G";
}
else
{
strNetworkType = "3G";
}
}
}
}
}
if (strNetworkType == "") {
strNetworkType = "WWAN";
}
NSLog( @"GetNetWorkType() strNetworkType : %s", strNetworkType.c_str());
return strNetworkType;
}
参考链接:
http://blog.csdn.net/justinjing0612/article/details/8741261
http://www.jianshu.com/p/efcfa3c87306
http://www.cnblogs.com/xiaohuzi1990/p/4341655.html
标签:
原文地址:http://www.cnblogs.com/meteoric_cry/p/4628490.html