Hi,我是White.tian。本文为原创,转载请注明出处。
大家在开发过程中,不乏会用到有时候获取手机是否联网,或者是当前的网络连接状态等。那么即有了以下内容。
根据状态栏获取网络状态,可以区分2G、3G、4G、WIFI,系统的方法,比较快捷。稍微不爽的就是万一连接的WIFI没有联网的话。
下面为代码区域
intDemoCodeClass::getDeviceNetworkAvailabl()
{
UIApplication *app = [UIApplicationsharedApplication];
NSArray *children = [[[appvalueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
int stateNumber =0;
NSString *state = [[NSStringalloc]init];
int netType =0;
state = @"false";
//获取到网络返回码
for (id childin children) {
if ([childisKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
//获取到状态栏
netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
NSLog(@"%d",netType);
switch (netType) {
case0:
//state = @"无网络";
state = @"false";
NSLog(@"%s","0,无网络");
stateNumber = 0;
//无网模式
break;
case1:
//state = @"2G";
state = @"true";
NSLog(@"%s","1,2G");
stateNumber = 1;
break;
case2:
//state = @"3G";
state = @"true";
NSLog(@"%s","2,3G");
stateNumber = 1;
break;
case3:
//state = @"4G";
state = @"true";
NSLog(@"%s","3,4G");
stateNumber = 1;
break;
case5:
{
//state = @"WIFI";
state = @"true";
NSLog(@"%s","5,WIFI");
stateNumber = 1;
break;
}
default:
break;
}
}
}
//根据状态选择
//return state;
constchar *content = [statecStringUsingEncoding:NSASCIIStringEncoding];
//return content;
return stateNumber;
}
//state = @"无网络";
//state = @"2G";
//state = @"3G";
//state = @"4G";
//state = @"WIFI";
最后根据stateNumber值来判断就OK了。