iOS获取当前网络状态
2017-10-26 本文已影响92人
Macanzy
自己工作中用到的,在此记录一下,希望对大家有帮助。
- (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;
}