CoreBluetooth“willRestoreState” - 到底应该在那里做什么?

dor*_*506 5 objective-c ios core-bluetooth bluetooth-lowenergy cbcentralmanager

我正在开发一个需要持续运行和跟踪一些外围特性的应用程序。

在前台一切正常。
它也可以在后台运行,但我不确定我是否正确执行。

我红了很多关于状态恢复和实施的帖子 willRestoreState,但其中很多都没有明确告诉你当这个方法被调用时该怎么做。

我正在制作的过程是这样的:

我正在创建一个中央管理器使用

myCentralManager =
        [[CBCentralManager alloc] initWithDelegate:self queue:nil
         options:@{ CBCentralManagerOptionRestoreIdentifierKey:
         @"myCentralManagerIdentifier" }];
Run Code Online (Sandbox Code Playgroud)

从这里我正在做以下常规流程
等待中央管理器启动 (centralManagerDidUpdateState) -> 扫描我的外围设备 -> 连接到它 -> 发现服务 -> 发现特征 -> 订阅特征 -> 阅读数据

然后我使用杀死我的应用程序

kill(getpid(), SIGKILL);
Run Code Online (Sandbox Code Playgroud)

我正在等待几秒钟,然后再次从我的外围设备开始做广告。

然后我可以看到该过程正在恢复生机,并且我的日志显示didFinishLaunchingWithOptionsAppDelegate 正在被调用。

然后我像这样恢复中央管理器:

 NSArray *identifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

   if (identifiers && identifiers.count > 0) {
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self
                                                               queue:nil
                                                             options:@{CBCentralManagerOptionRestoreIdentifierKey:[identifiers objectAtIndex:0]}];
    } 
Run Code Online (Sandbox Code Playgroud)

我也可以看到willRestoreState并被centralManagerDidUpdateState调用。

这就是我迷路的地方。我接下来该怎么做?如果我继续执行常规流程(我在上面描述过,所有似乎都可以正常工作 - 并且与上述方式相同。

但是——我做的对吗?

我应该做些什么willRestoreState吗?如果是,我应该怎么做?

提前致谢!

小智 5

基本上,您将返回已连接的外围设备 - 您应该保存对它的引用并为自己设置它的委托。这是我的代码,非常简单:

   - (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict
 {
      //get the handle to the peripheral already connected by the os and set ourselves as the delegate
      NSArray *peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey];
      if (peripherals.count > 0){
        CBPeripheral* pr = peripherals[0];
        // Set peripheral required values and start discovering services
        [pr setDelegate:self];
        [pr readRSSI];
        [pr discoverServices:nil];
      }
}
Run Code Online (Sandbox Code Playgroud)