1.蜂窝权限状态获取
检查应用的蜂窝权限,可使用CTCellularData类
#import <CoreTelephony/CTCellularData.h>
- 创建CTCellularData实例,监听蜂窝权限的变化,注意:这个CTCellularData实例需要设置成全局变量,在需要获取蜂窝权限状态的场景下使用这个对象
static CTCellularData *_cellularData;
- (void)addObserverForWWAN {
_cellularData = [CTCellularData new];
_cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
switch (state) {
case kCTCellularDataRestricted:
NSLog(@"蜂窝-变化-受限");
break;
case kCTCellularDataNotRestricted:
NSLog(@"蜂窝-变化-不受限");
break;
default:
NSLog(@"蜂窝-变化-未知");
break;
}
};
}
当添加这个监听时,会立即执行一次上面这个block回调.
- 获取当前蜂窝权限
+ (CTCellularDataRestrictedState)stateOfWWAN {
return _cellularData.restrictedState;
}
2. 判断蜂窝是否开启
网上找了很久没找到对应的方法,只找到判断wifi开启状态的方法,这个判断蜂窝开启的方法由此演化得来(在iOS12,iOS10上面测试均有效)
- 导入头文件
#import <net/if.h>
#import <ifaddrs.h>
- 关键代码
+ (BOOL)isWWANEnable {
NSCountedSet *countedSet = [NSCountedSet new];
struct ifaddrs *interfaces;
if (!getifaddrs(&interfaces)) {
for (struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) {
if ((interface->ifa_flags & IFF_UP) == IFF_UP) {
NSString *ifa_name = [NSString stringWithUTF8String:interface->ifa_name];
[countedSet addObject:ifa_name];
NSLog(@"ifa_name: %s, sa_family: %d", interface->ifa_name, interface->ifa_addr->sa_family);
}
}
}
freeifaddrs(interfaces); // 需要手动释放
BOOL open = [countedSet countForObject:@"pdp_ip0"] > 1 ? YES : NO;
NSLog(@"cellular open status: %@", open ? @"open" : @"unopen");
return open;
}
当没有打开蜂窝时,pdp_ip0个数为0, 当打开蜂窝时,pdp_ip0个数有4个
网友评论