1. 程式人生 > >iOS 手機網路型別和運營商怎麼獲取

iOS 手機網路型別和運營商怎麼獲取

Reachability 只能判斷是WiFi還是蜂窩網路,無法獲取到具體的型別是3G還是4G,現在獲取手機網路型別可以直接使用蘋果原生API了:

首先我們匯入庫  CoreTelephony.framework

然後在我們的類中加入下面標頭檔案

#import <CoreTelephony/CTTelephonyNetworkInfo.h>  
#import <CoreTelephony/CTCarrier.h>  

下面是獲取網路環境的方法:

基本原理是從UIApplication型別中通過valueForKey獲取內部屬性statusBar。然後篩選一個內部型別(UIStatusBarDataNetworkItemView),最後返回他的dataNetworkType屬性。


//獲取聯網方式
-(NSString *)networkType
{
    NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
            break;
        }
    }
    NSString *networkType = nil;
    switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"] integerValue]) {
        case 0:
            networkType = @"無服務";
            break;
            
        case 1:
            networkType = @"2G";
            break;
            
        case 2:
            networkType = @"3G";
            break;
            
        case 3:
            networkType = @"4G";
            break;
            
        case 4:
            networkType = @"LTE";
            break;
            
        case 5:
            networkType = @"Wifi";
            break;
            
        default:
            break;
    }
    return networkType;
}

下面是如何獲取運營商名稱:
//獲取運營商資訊
-(NSString *)getCarrierName
{
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
    NSString *currentCountry = [carrier carrierName];
    return currentCountry;
}
轉自:http://blog.csdn.net/dean19900504/article/details/44648583