你可以在Github下载这个Demo https://github.com/JanzTam/Reachability_Demo
首先,引入系统的Reachability类,不知道怎么引入的话,在Xcode,按下shift+command+0,搜索Reachability,看到图中所选的工程下载即可。
Reachability.png
并导入相关.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;
}
}
时间: 2024-10-05 05:31:36