3

我有以下场景:iOS 应用程序(外围)X OSX 应用程序(中央)

  • 我用 CBPeripheralManagerOptionRestoreIdentifierKey 实例化我的外设管理器。
  • 在我的外围设备的 didFinishLaunchingWithOptions 中,我在使用 UIApplicationLaunchOptionsBluetoothPeripheralsKey 获取外围设备后发送本地通知(不要对它做任何事情)
  • 在我的外围设备的 willRestoreState 中,我还触发了一个通知(除此之外不要做任何事情)

如果我的外围应用程序在由于内存压力而被杀死之前仍在后台运行,我会从 OSX 中心收到消息。

在 iOS 应用程序被杀死后,当 OSX 中心发送消息时,上面提到的两个通知都会在 iOS 上通过,但我实际上期待的消息并没有。

我在任何时候都没有对我的 peripheralManager 进行 rentantiated,我应该在哪里以及如何做呢?我的应用程序的整个周期只有一个 peripheralManager。

欢迎任何建议。

更新:

如果这样做

let options: Dictionary = [CBPeripheralManagerOptionRestoreIdentifierKey: "myId"]
peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)

在 willRestoreState 中,我的应用程序只是失去了连接

4

1 回答 1

2

是的,在重新审视了关于这个问题的所有主题 100 次之后,我终于弄明白了,这正是它应该如何实现的:

在 AppDelegate 的 didFinishLaunchingWithOptions 中:

if let options = launchOptions {
    if let peripheralManagerIdentifiers: NSArray = options[UIApplicationLaunchOptionsBluetoothPeripheralsKey] as? NSArray {

        //Loop through peripheralManagerIdentifiers reinstantiating each of your peripheralManagers
        //CBPeripheralManager(delegate: corebluetooth, queue: nil, options: [CBPeripheralManagerOptionRestoreIdentifierKey: "identifierInArray"])

    }
    else {
        //There are no peripheralManagers to be reinstantiated, instantiate them as you normally would
    }
}
else {
    //There is nothing in launchOptions, instantiate them as you normally would
}

此时, willRestoreState 应该开始被调用,但是,如果您有一个来管理订阅您的特征的所有中心,那么您的中心阵列中将没有中心。由于我所有的中心总是在我拥有的一个服务中订阅我的所有特征,我只是循环遍历任何特征中的所有 subscribedCentrals,将它们重新添加到我的中心数组中。

请根据您的需要进行修改。

在 willRestoreState 中:

var services = dict[CBPeripheralManagerRestoredStateServicesKey] as! [CBMutableService]

if let service = services.first {

    if let characteristic = service.characteristics?.first as? CBMutableCharacteristic {

        for subscribedCentral in characteristic.subscribedCentrals! {
            self.cbCentrals.append(subscribedCentral as! CBCentral)
        }

    }

}

在此之后,您应该可以调用您准备与任何中央通信的任何方法,即使您同时处理其中的几个。

祝你好运!

于 2015-10-06T17:22:00.280 回答