Three methods of judging the current network state by IOS

Time:2021-5-12

In the project, in order to have a good user experience, some scenarios have to judge the network state before deciding what to do. For example, when playing video, you need to judge whether it is WiFi or 4G. WiFi plays directly, and 4G prompts the user first. There are three ways to get the network state

1. Reachability

This is the method used in Apple’s official demo. We can download the demo from Apple’s official document (click download sample code in the upper left corner to download it), then test the feasibility. H and. M in the demo into our own project, and add the systemconfiguration. Framework framework to the link binary of build phases, Then import the feasibility header file where you need to use it

In the connectivity header file, we can see the enumeration values of no network, WiFi and cellular network states, as follows:


typedef enum : NSInteger {
    NotReachable = 0,
    ReachableViaWiFi,
    ReachableViaWWAN
} NetworkStatus;

(1) Get network status

Before IOS 7, when the user network is a cellular network, it is impossible to judge the type of 3G, 4G and other networks. After IOS 7, it can be judged

(NSString *)internetStatus {
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"WIFI";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"WIFI";
            break;
        case ReachableViaWWAN:
            Net = @ "cellular data";
            //net = [self getNetType ];   // Judge the specific type
            break;
        case NotReachable:
            Net = @ "no network connection at present";
        default:
            break;
    }
    return net;
}

(2) When the user is the mobile phone’s own network, judge the specific network type

At this time, you can use the API provided by the system to determine whether it is 2G, 3G or 4G. You need to use cttelephony networkinfo. Remember to add coretelephony.framework to the project and import the header file


- (NSString *)getNetType
{
    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";
    }
}

The cellular network types judged by this method are as follows:

CTRadioAccessTechnologyGPRS          // Between 2G and 3G, also known as 2.5G  , Over technology

CTRadioAccessTechnologyEdge          // Edge is the transition from GPRS to 3G, commonly known as 2.75g

CTRadioAccessTechnologyWCDMA

CTRadioAccessTechnologyHSDPA             // Also known as 3.5G (3? G)

CTRadioAccessTechnologyHSUPA             // Transition technology from 3G to 4G

CTRadioAccessTechnologyCDMA1x       //3G

CTRadioAccessTechnologyCDMAEVDORev0     // 3G standard

CTRadioAccessTechnologyCDMAEVDORevA

CTRadioAccessTechnologyCDMAEVDORevB

CTRadioAccessTechnologyeHRPD         // An evolution technology from 3G to 4G used by telecom,   3.75G

CTRadioAccessTechnologyLTE           // Close to 4G

2. Judge by system status bar

This method may cause a crash on iPhone X. Apple may modify the keypath of the statusbar, so it gets nil, causing a crash / / getting the current network state   ( iPhone   X   May cause a crash)

+ (NSString *)networkingStatesFromStatebar {
    //   The status bar is controlled by the current app. First, get the current app
    UIApplication *app = [UIApplication sharedApplication];
    //iphone   X   It's going to collapse here
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    NSString *stateString = @"wifi";
    switch (type) {
        case 0:
            stateString = @"notReachable";
             break;
        case 1:
            stateString = @"2G";
            break;
        case 2:
            stateString = @"3G";
            break;
        case 3:
            stateString = @"4G";
            break;
        case 4:
            stateString = @"LTE";
            break;
        case 5:
            stateString = @"wifi";
            break;
        default:
            break;
    }
    return stateString;
}

3. Through afnetworking

This method can be written in appdelegate. Whenever the network state changes, it can send a notice, monitor the network change in real time, and then do the corresponding processing

#Monitor network status-------------
- (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                Nslog (@ "unknown network");
                break;
            case 0:
                Nslog (@ "network unreachable");
                break;
            case 1:
                {
                Nslog (@ "GPRS network");
                //Give notice and take the lead
                [[NSNotificationCenter defaultCenter] postNotificationName:@"monitorNetworking" object:@"1" userInfo:nil];
                }
            break;
            case 2:
                {
                Nslog (@ "WiFi network");
                //Send a notice, do something
                [[NSNotificationCenter defaultCenter] postNotificationName:@"monitorNetworking" object:@"2" userInfo:nil];
                }
                break;
            default:
                break;
        }
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            Nslog (@ "with network");
        }else{
            Nslog (@ "no network");
        }
    }];
}

The above is the detailed content of the three methods of IOS judging the current network state. For more information about IOS judging the current network state, please pay attention to other related articles of developer!

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]