我正在尝试在后台模式下使用 corebluetooth 连接到 BLE 设备。我已经有后台模式工作,目前在后台接收断开回调。
我这样创建经理
centralManager = CBCentralManager(delegate: self, queue: nil,
options: [CBCentralManagerOptionRestoreIdentifierKey: "myCentralManagerIdentifier"])
然后我用
centralManager.scanForPeripherals(withServices: nil,
options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
然后我在扫描后连接到设备
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
if peripheral.name == "My BLE" {
self.peripheral = peripheral
self.peripheral.delegate = self
centralManager.stopScan()
// Connect!
centralManager.connect(self.peripheral, options: nil)
}
}
现在,当应用程序在后台运行并且 BLE 断开连接时,我收到了这个回调(这很好,它表明后台模式和状态恢复正在工作)
func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?)
{
print("Disconnected")
peripheral.delegate = self
centralManager.connect(peripheral, options: nil)
}
我立即尝试重新连接。但即使设备重新上线,我也从未收到任何回电。我的印象是,这个 API 的工作方式是操作系统会在我的应用程序处于后台时为我尝试连接,而当 BLE 重新联机时,我会收到通知吗?
我有以下委托方法让我知道它何时连接
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
//send some user notifications and logs
alert()
}
didConnect 在建立第一个连接时被调用,但在 BLE 设备在后台恢复在线时不会被调用
根据苹果文档
当用户离开家时,iOS 设备最终可能会超出锁的范围,导致与锁的连接丢失。此时,应用程序可以简单地调用CBCentralManager类的connectPeripheral:options:方法,由于连接请求不会超时,所以当用户回到家时,iOS设备会重新连接。