接上一篇《ios 蓝牙扫描 UUID(scanForPeripheralsWithServices)》,发现后台扫描问题,除去首次扫描无法锁屏后台完成,那么以怎样的方式才能完成在有效范围内能重连成功呢?
可能有小伙伴会提出以下方式,该方式具体如何使用就不做累述,跟着代理一步步实现就行
* @seealso CBCentralManagerOptionShowPowerAlertKey
* @seealso CBCentralManagerOptionRestoreIdentifierKey
*
*/
- (instancetype)initWithDelegate:(nullable id<CBCentralManagerDelegate>)delegate
queue:(nullable dispatch_queue_t)queue
options:(nullable NSDictionary<NSString *, id> *)options;
在该方法中,将options 中 CBCentralManagerOptionRestoreIdentifierKey 为一个固定串
//然后实现代理方法
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict{}
由于公司项目的外设性质决定,上述方式不适用,于是采取使用identifier(也就是CBPeripheral 中的一个参数)做重连操作,当是所需要的设备时,将identifier 做本地缓存。使用如下
//参数说明
//@discussion The unique, persistent identifier associated with the peer.
@property(readonly, nonatomic) NSUUID *identifier NS_AVAILABLE(10_13, 7_0);
//使用姿势
CBCentralManager *bluManager = xxxxx;//项目中创建的
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"缓存的uuid字符串"];
if(!uuid) {
return;
}
NSArray<CBPeripheral *> *peripherals = [bluManager retrievePeripheralsWithIdentifiers:@[uuid]];
if(!peripherals || peripherals.count == 0) {
return;
}
[bluManager connectPeripheral:peripherals.firstObject options:nil];
补充: 如何监听锁屏状态
- (void)checkDeviceScreenState {
int notify_token;
notify_register_dispatch("com.apple.springboard.lockstate",
¬ify_token,dispatch_get_main_queue(),
^(int token) {
uint64_t state = UINT64_MAX;
notify_get_state(token, &state);
NSLog(@"%@",state == 1?@"锁屏状态":@"非锁屏状态");
});
}
以此方式进行重连,查看ios 系统蓝牙数据包可以看到系统会自动维护。下图是抓包系统蓝牙数据包截图:
后面将补充,如何进行ios端系统蓝牙抓包