您的位置:首页 > 理论基础 > 计算机网络

ios如何获取手机的网络状态和运营商名称

2015-03-26 13:18 603 查看
以前获取手机的网络状态和运营商名称都是似有API,

现在我们可以大胆使用这些API了,完全可以通过审核。

具体方法如下,首先我们导入

CoreTelephony.framework

然后在我们的类中加入下面头文件

[html] view
plaincopy





#import <CoreTelephony/CTTelephonyNetworkInfo.h>

#import <CoreTelephony/CTCarrier.h>

下面是获取网络环境的方法:

[html] view
plaincopy





-(void)networktype{

NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];

NSNumber *dataNetworkItemView = nil;

for (id subview in subviews) {

if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {

dataNetworkItemView = subview;

break;

}

}

switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {

case 0:

NSLog(@"No wifi or cellular");

infoLabel.text=@"无服务";

break;

case 1:

NSLog(@"2G");

infoLabel.text=@"2G";

break;

case 2:

NSLog(@"3G");

infoLabel.text=@"3G";

break;

case 3:

NSLog(@"4G");

infoLabel.text=@"4G";

break;

case 4:

NSLog(@"LTE");

infoLabel.text=@"LTE";

break;

case 5:

NSLog(@"Wifi");

infoLabel.text=@"Wifi";

break;

default:

break;

}}

下面是如何获取运营商名称:

[html] view
plaincopy





-(void)getcarrierName{

CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];

CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];

NSString *currentCountry=[carrier carrierName];

NSLog(@"[carrier isoCountryCode]==%@,[carrier allowsVOIP]=%d,[carrier mobileCountryCode=%@,[carrier mobileCountryCode]=%@",[carrier isoCountryCode],[carrier allowsVOIP],[carrier mobileCountryCode],[carrier mobileNetworkCode]);

serverLabel.text=currentCountry;

}

控制台打印的log

[html] view
plaincopy





2014-07-31 11:14:15.919 PingDemo[2469:60b] networktype=Wifi

2014-07-31 11:14:15.926 PingDemo[2469:60b] [carrier isoCountryCode]==cn,[carrier allowsVOIP]=1,[carrier mobileCountryCode=460,[carrier mobileCountryCode]=01

其中isoCountryCode使用ISO 3166-1标准,参考:http://en.wikipedia.org/wiki/ISO_3166-1

mobileCountryCode(MCC)和mobileNetworkCode(MNC)可以参考:http://en.wikipedia.org/wiki/Mobile_country_code

真是手机截图:(我们用2G的网络来测试完全ok)



最近又看了下这个framework,发现了一个新的通知,可以用来玩玩,但是我个人感觉用处不大。

subscriberCellularProviderDidUpdateNotifier

用法:

[html] view
plaincopy





self.telephonyInfo.subscriberCellularProviderDidUpdateNotifier = ^(CTCarrier *carrier) {

dispatch_async(dispatch_get_main_queue(), ^{

NSLog(@"这个是什么啊");

});

};

这个我测试了下,只有手机还SIM 才会又这个通知,实用性不大。

假如有一天ios有手机处于弱网环境的通知就好了。

呵呵!

转载自justinjing的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐