iOS获取当前网络类型(Wifi、2G、3G、4G)

在工程添加:SystemConfiguration.framework

去苹果API里搜索Reachability,下载Demo(点击左上角Download Sample Code 即可下载),把demo里的Reachability.h和Reachability.m拖到自己的工程里。也可以在百度里面搜索”Reachability”,然后下载,不一定非要到苹果官网去下载。

但是使用Reachability有一个问题,就是它只能判断当前是Wifi或者手机自带网络,没有办法详细得判断2G、3G、4G。
如果确定为手机自带网络,这时可以使用系统自带的API来判断是2G、3G还是4G,这就要使用到CTTelephonyNetworkInfo这类,记得在工程添加CoreTelephony.framework

记得导入头文件:

import "Reachability.h"

import <CoreTelephony/CTCarrier.h>

import <CoreTelephony/CTTelephonyNetworkInfo.h>

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

#import "Reachability.h"

#include <sys/param.h>

#include <sys/mount.h>

 #endif

下面附上我在项目中使用的代码:

+ (NSString *)getNetconnType{

    NSString *netconnType = @"";

    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];

    switch ([reach currentReachabilityStatus]) {
        case NotReachable:// 没有网络
        {

            netconnType = @"no network";
        }
            break;

        case ReachableViaWiFi:// Wifi
        {
            netconnType = @"Wifi";
        }
            break;

        case ReachableViaWWAN:// 手机自带网络
        {
            // 获取手机网络类型
            CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];

            NSString *currentStatus = info.currentRadioAccessTechnology;

            if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {

                netconnType = @"GPRS";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {

                netconnType = @"2.75G EDGE";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){

                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){

                netconnType = @"3.5G HSDPA";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){

                netconnType = @"3.5G HSUPA";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){

                netconnType = @"2G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){

                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){

                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){

                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){

                netconnType = @"HRPD";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){

                netconnType = @"4G";
            }
        }
            break;

        default:
            break;
    }

    return netconnType;
}
上一篇:CentOS 新增swap交换空间


下一篇:阿里云2G内存服务器构建Gitlab私服