本文主要是介绍关于获取当前网络是属于2G还是3G(极其简单),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
中国的iphone网络是区分2G和3G,要想获取当前的网络状态一直没有一个好的方法,网上给的例子也不尽让人满意最近闲来无事,仔细的研究Apple提供的例子:Reachability通过如下的代码:
- Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
- NSLog(@"%d", [reach currentReachabilityStatus]);
- return;
在currentReachabilityStatus函数中,我们注意到这样的输出:
- static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, c*****t char* comment)
- {
- #if kShouldPrintReachabilityFlags
- NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
- (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
- (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
- (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
- (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
- (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
- (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
- (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
- (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
- (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
- comment
- );
- #endif
- }
当是wifi的时候输出R
当是3G的时候输出Rt
当是联通2G或者是移动的时候输出Rtc
在头文件定义如下:
- typedef enum
- {
- NotReachable = 0,
- ReachableViaWiFi,
- ReachableVia3G,
- ReachableVia2G,//当前无法区分是联通的2G还是移动的2G
- } NetworkStatus;
因此我就是以这个为判断条件的,重写Reachability的函数:
- - (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
- {
- if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
- {
- return NotReachable;
- }
- BOOL retVal = NotReachable;
- 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
- retVal = ReachableViaWiFi;
- }
- 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
- retVal = ReachableViaWiFi;
- }
- }
- if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
- {
- retVal = ReachableVia3G;
- if((flags & kSCNetworkReachabilityFlagsReachable) == kSCNetworkReachabilityFlagsReachable)
- {
- if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection)
- {
- retVal = ReachableVia3G;
- if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired)
- {
- retVal = ReachableVia2G;
- }
- }
- }
- }
- return retVal;
- }
这样就可以正确的区分是2G,3G,wifi网络,这只支持中国地区,其他地区未考虑。
作者:Rush.D.Xzj
欢迎转载 转载请注明来源
这篇关于关于获取当前网络是属于2G还是3G(极其简单)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!