首页 > 解决方案 > 应用终止时CoreBluetooth建立外围连接

问题描述

我有一个 iOS 应用程序,它通过 CoreBluetoothcentral连接到外部。peripheral

连接到 后peripheral,我对其进行读取和写入数据,然后断开连接。断开连接后,我尝试再次建立连接,以便下次peripheral进入advertise模式时,应用程序将连接到它,如下所示:

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    central.connect(peripheral, options: nil)
    // More actions here...
}

当应用程序位于 / 时,它工作得很好,但当应用程序位于foreground/backgroundterminated,它根本不起作用。

我已经定义了CBCentralManager这样的CBCentralManagerOptionRestoreIdentifierKey

self.central = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: Application.bluetoothRestoreIdentifier])

我还实现了willRestoreState中央委托方法:

func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any])

我究竟做错了什么?

非常感谢!

标签: iosswiftcore-bluetooth

解决方案


试试下面的代码

func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
        let connectedperipherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral]
        if let peripheral = connectedperipherals?.first {
            central.connect(peripheral, options: nil)
        }
    }

推荐阅读