美文网首页
iOS获取当前网络状态

iOS获取当前网络状态

作者: Macanzy | 来源:发表于2017-10-26 10:23 被阅读92次

    自己工作中用到的,在此记录一下,希望对大家有帮助。

    - (NetWork_State_Type)getNetWorkStates{
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
        NetWork_State_Type state = NetWork_State_NoNet;
        int netType = 0;
        //获取到网络返回码
        for (id child in children) {
            if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
                //获取到状态栏
                netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
                
                switch (netType) {
                    case 0:
                        state = NetWork_State_NoNet;//无网络
                        break;
                    case 1:
                        state = NetWork_State_2G;//2G
                        break;
                    case 2:
                        state = NetWork_State_3G;//3G
                        break;
                    case 3:
                        state = NetWork_State_4G;//4G
                        break;
                    case 5:
                        state = NetWork_State_WiFi;//WiFi
                        break;
                    case 6:
                        state = NetWork_State_HotSpot;//热点
                    default:
                        break;
                }
            }
        }
        //根据状态选择
        return state;
    }
    

    相关文章

      网友评论

          本文标题:iOS获取当前网络状态

          本文链接:https://www.haomeiwen.com/subject/snmhpxtx.html