日常收录

iOS开发之网络监听

2020-09-30  本文已影响0人  悄然林静
iOS监听网络方式 缺点
通过状态栏判断 一旦状态栏隐藏就会失效
AFNetworking中的网络监听模块 必须导入该框架,且无法判断移动网络的具体类型
Reachability + CTTelephonyNetworkInfo 代码较多

Reachability + CTTelephonyNetworkInfo

Reachability官网下载

Reachability 中的网络类型:

上面可以看出,Reachability 并没有区分蜂窝移动网络的具体类型(例如2G/3G/4G),因此还需要配合 CTTelephonyNeiworkInfo 使用。

CTTelephonyNetworkInfo 中的蜂窝移动网络类型:

集成Reachability + CTTelephonyNetworkInfo的步骤

/**
 *  判断当前网络类型
 */
+ (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;
}
上一篇下一篇

猜你喜欢

热点阅读