Objective-C determine data network type of the iOS device

淺唱寂寞╮ 提交于 2019-11-28 16:21:18

问题


Im on an application that receive data from server, the problem is when user connect to cellular data (Not 3G or WIFI), it take ages to receive data.

i had implemented this code from this Answer but im not sure if it is effective or not, sometimes it's giving me an accurate type, and sometimes it don't.

here is my code:

- (void)newtworkType {

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;
    }
}

switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {
    case 0:
        NSLog(@"No wifi or cellular");
        break;

    case 1:
        NSLog(@"2G");
        break;

    case 2:
        NSLog(@"3G");
        break;

    case 3:
        NSLog(@"4G");
        break;

    case 4:
        NSLog(@"LTE");
        break;

    case 5:
        NSLog(@"Wifi");
        break;


    default:
        break;
}}

is this the best i can do??, i tried Apple Reachability example, but it can determine if reachabilityForInternetConnection or just reachabilityForLocalWiFi but that not helpfull in my case.

Thanks in advance.


回答1:


Make sure that the Status bar is not hidden in your application. if it's not visible it will always return No wifi or cellular because your code reads the text in the Status bar thats all.

this is the best way to solve your problem, just make the Status bar not hidden then the application will get the text about the network type.




回答2:


if using iOS 7+ then you can get information from CoreTelephony framework following method :

CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
NSLog(@"Current Radio Access Technology: %@", telephonyInfo.currentRadioAccessTechnology);

Possibles values defined which you will get are as follows : CTRadioAccessTechnologyGPRS, CTRadioAccessTechnologyEdge ,CTRadioAccessTechnologyWCDMA , CTRadioAccessTechnologyLTE etc




回答3:


case 1, with the NSLog(@"2G"); is the case where the phone is on regular cellular data, not 3G, not 4G, and not WiFi.

What you should do is insert code below the NSLog for 2G to prevent the data transfer.



来源:https://stackoverflow.com/questions/16774885/objective-c-determine-data-network-type-of-the-ios-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!