后台唤醒的前提是:需要定位“始终允许”权限;
background modes 中开启Uses Bluetooth LE accessoriesself.cbManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
一调用,就会走代理- (void)centralManagerDidUpdateState:(CBCentralManager *)central
。self.cbManager = [[CBCentralManager alloc] initWithDelegate:self
cbManager初始化后马上取状态,会得到CBCentralManagerStateUnknown状态,尽管此时蓝牙打开。猜测此时还未初始化完成,所以返回unknown。
queue:nil]; CBCentralManagerState state = self.cbManager.state;
- self.cbManager = [[CBCentralManager alloc] initWithDelegate:self
queue:nil];这么初始化,如果蓝牙是关闭的,会弹出“打开蓝牙来允许“XXX“连接到配件“提示框。如果不想弹出,可换另一种初始化方式
- self.cbManager = [[CBCentralManager alloc] initWithDelegate:self
NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey:@NO};
self.cbManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
当options传nil,也不会弹出窗口。
- iOS 11之后,设置中蓝牙开启,而控制中心蓝牙关闭,centralManagerDidUpdateState会返回 CBCentralManagerStatePoweredOff。
[CoreBluetooth] API MISUSE: <CBCentralManager: 0x1c02799c0> can only accept this command while in the powered on state
终端出现这句提示,表示调用[self.cbManager scanForPeripheralsWithServices:nil options:nil];时机不对,只有确定蓝牙开启后,才能调用。- 使用蓝牙时,苹果要求在plist中添加请求权限NSBluetoothPeripheralUsageDescription,但是它并没有类似定位、相册等,弹出提示用户允许权限的提示框,可能为以后做铺垫吧。
- 不走didDetermineState回调,看看定位权限是否是“始终允许“。
未解决问题:
- 在iOS11+系统上,应用定位是“永不“,设置中和控制中心蓝牙开关都是开启,启动应用,centralManagerDidUpdateState回调用返回off。有人说是系统bug,哪位同学了解可以交流下。
另外,Apple官方文档
其他资料:
监听蓝牙状态