ios 蓝牙使用 identifier 创建设备进行重连

接上一篇《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",

                             &notify_token,dispatch_get_main_queue(),

                             ^(int token) {

        uint64_t state = UINT64_MAX;

        notify_get_state(token, &state);

         NSLog(@"%@",state == 1?@"锁屏状态":@"非锁屏状态");

    });

}

以此方式进行重连,查看ios 系统蓝牙数据包可以看到系统会自动维护。下图是抓包系统蓝牙数据包截图:

后面将补充,如何进行ios端系统蓝牙抓包

  • 26
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值