iOS开发中,有时需要检测设备运营商类型,如移动、联通或者电信,本文以检测联通为例。
系统代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
- (BOOL)checkIsUnicom { CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init]; CTCarrier *carrier = info.subscriberCellularProvider; NSString *carrierName = carrier.carrierName; NSString *mobileCountryCode = carrier.mobileCountryCode; NSString *mobileNetworkCode = carrier.mobileNetworkCode; [info release]; if (!mobileNetworkCode) { return NO; } if ([mobileCountryCode intValue]==460) { //国内 return [carrierName rangeOfString:@"联通"].length>0 || [mobileNetworkCode isEqualToString:@"01"] || [mobileNetworkCode isEqualToString:@"06"]; } return [self statusBarCheckIsUnicom]; } |
运行商对应的NetworkCode
正常情况下,以上代码可满足正常需求,但是对于美版或者日版卡贴iPhone,检测到的CTCarrier并非sim卡信息,此时就需要通过StatusBar实时检测当前网络运行商
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
- (BOOL)statusBarCheckIsUnicom { NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews]; UIView *serviceView = nil; Class serviceClass = NSClassFromString([NSString stringWithFormat:@"UIStat%@Serv%@%@", @"usBar", @"ice", @"ItemView"]); for (UIView *subview in subviews) { if([subview isKindOfClass:[serviceClass class]]) { serviceView = subview; break; } } if (serviceView) { NSString *carrierName = [serviceView valueForKey:[@"service" stringByAppendingString:@"String"]]; return [carrierName rangeOfString:@"联通"].length>0; } else { return NO; } } |
喜欢请点赞->https://github.com/panghaijiao,谢谢你的来访!
仔细拜读,表示支持!
甲午年(马)腊月初九 2015-1-28
学到了
支持一下,感谢你分享