iOS 开发获取当前的网络状态有很多种方式,下面我介绍的是通过获取手机状态栏中的网络状态,获取当前手机的所连网络的状态:《前提:状态栏不能影藏》。适配iOS 11
- (NSString *)backNetType{
NSString *stateString = @"";
NSArray * children;
UIApplication *application = [UIApplication sharedApplication];
if ([[application valueForKeyPath:@"_statusBar"] isKindOfClass:NSClassFromString(@"UIStatusBar_Modern")]) {
//适配iOS 11 获取不到网络状态
children = [[[[application valueForKeyPath:@"_statusBar"] valueForKeyPath:@"_statusBar"] valueForKeyPath:@"foregroundView"] subviews];
} else {
children = [[[application valueForKeyPath:@"_statusBar"] valueForKeyPath:@"foregroundView"] subviews];
}
int type = 0;
for (id child in children) {
if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
}
}
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;
}