中国的iphone网络是区分2G和3G,要想获取当前的网络状态一直没有一个好的方法,网上给的例子也不尽让人满意
最近闲来无事,仔细的研究Apple提供的例子:Reachability
通过如下的代码:
?
1
2
3
Reachability *reach = [Reachability reachabilityWithHostName:@"
www.apple.com"];
NSLog(@"%d", [reach currentReachabilityStatus]);
return;
在currentReachabilityStatus函数中,我们注意到这样的输出:
static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const 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
在头文件定义如下:
?
1
2
3
4
5
6
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;
}
}
?
1
2
3
4
5
6
7
8
9
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
retVal = ReachableVia3G;
if((flags & kSCNetworkReachabilityFlagsReachable) == kSCNetworkReachabilityFlagsReachable) {
if((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection) {
retVal = ReachableVia2G;
}
}
}
return retVal;
}
这样就可以正确的区分是2G,3G,wifi网络,这只支持中国地区,其他地区未考虑。
作者:Rush.D.Xzj