iOS网络监测如何区分2、3、4G?
转自:
http://www.jianshu.com/users/e2b4fcf4de34/latest_articles
你可以在
Github下载这个Demo
首先,引入系统的Reachability类,不知道怎么引入的话,在Xcode,按下shift+command+0,搜索Reachability,看到图中所选的工程下载即可。
并导入相关.h文件
import<CoreTelephony/CTTelephonyNetworkInfo.h>
引入后,Reachability.h文件里面修改NetworkStatus的枚举,
typedef enum : NSInteger { NotReachable = 0, ReachableViaWiFi, ReachableViaWWAN, kReachableVia2G, kReachableVia3G, kReachableVia4G} NetworkStatus;
在修改下Reachability.m文件找到
- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
修改下面的代码
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]) { returnValue = kReachableVia4G; } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) { returnValue = kReachableVia2G; } else { returnValue = kReachableVia3G; } return returnValue; } } if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection) { if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired) { returnValue = kReachableVia2G; return returnValue; } returnValue = kReachableVia3G; return returnValue; } returnValue = ReachableViaWWAN; }
如何使用?
在AppDelegate里加入
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ //设置状态栏 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault]; // 监测网络情况 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"]; [hostReach startNotifier];}
(void)reachabilityChanged:(NSNotification )note{ Reachability curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); NetworkStatus status = [curReach currentReachabilityStatus]; switch (status) { case NotReachable: break; case ReachableViaWiFi: case ReachableViaWWAN: break; case kReachableVia2G: break; case kReachableVia3G: break; case kReachableVia4G: break; }}
一起学习,一起进步!互相分享干货,探讨问题iOS进阶交流群:68045643(因群成员较多,为了群里有个好的环境,防止广告狗乱入,申请进群请提供github或者blog等证明你是开发者)