我有一个使用Corebluetooth并使用其后台服务的应用。我还需要长期的CoreBluetooth动作,所以我需要实现状态保存和恢复。我跟着Apple文档下面的链接https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html也观看了下面的WWDC 2013演示视频链接, https://developer.apple.com/videos/play/wwdc2013/703/ 首先,源代码是在Objective C中,我不熟悉它,我试图在swift3中转换它们。
然后,我使用下面显示的恢复标识符定义了CBCentralManager,
self.myCentralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "myCentralManager"])
然后,在下面添加了委托方法,
func centralManager( willRestoreState dict: [String : AnyObject]) {
let peripherals: [CBPeripheral] = dict[CBCentralManagerRestoredStatePeripheralsKey] as! [CBPeripheral]
for peripheral in peripherals {
self.peripherals.append(peripheral)
peripheral.delegate = self
}
}
最后在AppDelegate中执行了didFinishLaunchingWithOptions方法,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
if let peripheralManagerIdentifiers: [String] = launchOptions?[UIApplicationLaunchOptionsKey.bluetoothCentrals] as? [String]{
for identifier in peripheralManagerIdentifiers{
if (identifier == "myCentralManager"){
}
}
}
return true
}
当我调试,调用didFinishLaunchingWithOptions方法时,参数launchOptions?[UIApplicationLaunchOptionsKey.bluetoothCentrals]为零我认为是因为我第一次创建应用程序,然后在定义带有恢复标识符的CBCentralManager时出错,错误是“原因:”提供了一个恢复标识符,但委托没有实现centralManager:willRestoreState:method'“
我很困惑,谢谢你的帮助,
致以最诚挚的问候,