iOS开发之网络监听
2020-09-30 本文已影响0人
悄然林静
iOS监听网络方式 | 缺点 |
---|---|
通过状态栏判断 | 一旦状态栏隐藏就会失效 |
AFNetworking中的网络监听模块 | 必须导入该框架,且无法判断移动网络的具体类型 |
Reachability + CTTelephonyNetworkInfo | 代码较多 |
Reachability + CTTelephonyNetworkInfo
Reachability 中的网络类型:
-
NotReachable
,无网络链接 -
ReachableViaWiFi
,WiFi -
ReachableViaWWAN
,蜂窝移动网络
上面可以看出,Reachability 并没有区分蜂窝移动网络的具体类型(例如2G/3G/4G),因此还需要配合 CTTelephonyNeiworkInfo 使用。
CTTelephonyNetworkInfo 中的蜂窝移动网络类型:
-
CTRadioAccessTechnologyGPRS
,2G -
CTRadioAccessTechnologyEdge
,2G -
CTRadioAccessTechnologyWCDMA
,2G -
CTRadioAccessTechnologyHSDPA
,3G -
CTRadioAccessTechnologyHSUPA
,3G -
CTRadioAccessTechnologyCDMA1x
,3G -
CTRadioAccessTechnologyCDMAEVDORev0
,3G -
CTRadioAccessTechnologyCDMAEVDORevA
,3G -
CTRadioAccessTechnologyCDMAEVDORevB
,3G -
CTRadioAccessTechnologyeHRPD
,3G -
CTRadioAccessTechnologyLTE
,3G
集成Reachability + CTTelephonyNetworkInfo的步骤
- 下载
Reachability.h
、Reachability.m
,并导入项目中 - 添加
CoreTelephony.framework
(Targets → Build Phases → Link Binary With Libraries
) - 导入头文件
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
/**
* 判断当前网络类型
*/
+ (NSString *)getNetworkType {
Reachability * reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
NetworkStatus netStatus = [reachability currentReachabilityStatus];
NSString * networkType = @"";
switch (netStatus) {
case ReachableViaWiFi:
networkType = @"WIFI";
break;
case ReachableViaWWAN: {
// 判断蜂窝移动类型
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
if (@available(iOS 12.0,*)) {
NSDictionary<NSString *, NSString *> *infoDic = networkInfo.serviceCurrentRadioAccessTechnology;
NSLog(@"infoDic = %@", infoDic);
} else {
if ([networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA]) {
networkType = @"2G";
} else if ([networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] ||
[networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
networkType = @"3G";
} else if ([networkInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
networkType = @"4G";
}
}
}
break;
case NotReachable:
networkType = @"当前无网络连接";
break;
}
return networkType;
}