iOS如何获得网络状态相关信息
2016-07-16 本文已影响1556人
子达如何
- 运营商信息: 直接使用CTTelephonyNetworkInfo的服务即可获得运营商的名字, 运营商编码等信息. easy!
-(NSString *)currentCarrierName{
CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
return [[NSString alloc] initWithFormat:@"%@_%@_%@_%@", [carrier carrierName], [carrier mobileCountryCode], [carrier mobileNetworkCode], [carrier isoCountryCode]];
}
- 当前网络类型(WiFi/4G) 信号强弱
Google到的一个文章, 大致是访问statusBar的视图, 然后KVC访问该视图的属性, 从而得到想要的信息.
文章没有提到如何获得信号强度, 不过, 顺着它的思路, 很快就找到了关键点:
类:**UIStatusBarDataNetworkItemView**, **UIStatusBarSignalStrengthItemView**
属性:**dataNetworkType**, **wifiStrengthBars**, **signalStrengthBars**
详细代码如下:
-(NSString *)currentNetworkType{
NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;
NSNumber *signalStrengthItemView = nil;
for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
}
if ([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]]) {
signalStrengthItemView = subview;
}
if (dataNetworkItemView && signalStrengthItemView) {
break;
}
}
if (!dataNetworkItemView) {
return nil;
}
NSNumber *networkTypeNum = [dataNetworkItemView valueForKey:@"dataNetworkType"];
NSNumber *wifiStrengthBars = [dataNetworkItemView valueForKey:@"wifiStrengthBars"];
NSNumber *signalStrengthBars = [signalStrengthItemView valueForKey:@"signalStrengthBars"];
if (!networkTypeNum) {
return nil;
}
NSInteger networkType = [networkTypeNum integerValue];
switch (networkType) {
case 0:
return @"No Service";
break;
case 1:
return [[NSString alloc] initWithFormat:@"%@_%@", @"2G", signalStrengthBars];
break;
case 2:
return [[NSString alloc] initWithFormat:@"%@_%@", @"3G", signalStrengthBars];
break;
case 3:
return [[NSString alloc] initWithFormat:@"%@_%@", @"4G", signalStrengthBars];
break;
case 4:
return [[NSString alloc] initWithFormat:@"%@_%@", @"LTE", signalStrengthBars];
break;
case 5:
return [[NSString alloc] initWithFormat:@"%@_%@", @"WiFi", wifiStrengthBars];
break;
default:
return [[NSString alloc] initWithFormat:@"%@_%@_%@", networkTypeNum, wifiStrengthBars, signalStrengthBars];
break;
}
}
- 授之以渔
我是怎么知道上面说的这些类有什么可以访问的属性的呢?
答案是借助一个杰出的开源库YYModel.
当然, 自己用OC的runtime方法写也是可以的, 只是没有用YYModel已经封装好的方法方便.
#import "YYModel.h"
//...
YYClassInfo *info = [YYClassInfo classInfoWithClass:[signalStrengthItemView class]];
NSLog(@"dataNetworkItemView ivars:%@", info.ivarInfos);
NSLog(@"dataNetworkItemView properties:%@", info.propertyInfos);
NSLog(@"dataNetworkItemView method:%@", info.methodInfos);
- 结束:)