我正在尝试创建一个连接到BP袖带的应用程序。我想在应用程序中启用状态恢复,这样即使应用程序被系统杀死,当BP袖带可用并传输时,仍然可以调用应用程序。以下是我到目前为止尝试过的一些事情。
1)向centralManager init添加资源标识符并为其分配后台串行队列
var ble_dispatchQueue = DispatchQueue(label: "com.xyz.ios.ble")
let opts = [CBCentralManagerOptionShowPowerAlertKey : true, CBCentralManagerOptionRestoreIdentifierKey:
"ios.xyz.ble.peripheral.identifier"] as [String : Any]
self.centralManager = CBCentralManager(delegate : self, queue : ble_dispatchQueue, options : opts)
2)实现willRestoreState和centralManagerDidUpdateState
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
print("will restore state called")
if let peripheralsObject = dict[CBCentralManagerRestoredStatePeripheralsKey] {
// 2
let peripherals = peripheralsObject as! Array<CBPeripheral>
// 3
if peripherals.count > 0 {
// 4
self.peripheralDevice = peripherals[0]
// 5
self.peripheralDevice?.delegate = self
}
}
}
centralManagerDidUpdateState:
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state != .poweredOn {
self.peripheralDevice = nil
return
}
startScan()
// 1
guard let peripheral = self.peripheralDevice else {
return
}
// 2
guard peripheral.state == .connected else {
return
}
// 3
guard let peripheralServices = peripheral.services else {
return
}
// 4
serviceUUID = deviceParameters.deviceTypeUUIDs![0]
if let serviceIndex = peripheralServices.index(where: {$0.uuid == serviceUUID}) {
let ANDService = peripheralServices[serviceIndex]
let characteristicUUIDs = deviceParameters.deviceCharacteristicUUIDs
if let cUUIDs = characteristicUUIDs, let characteristics = ANDService.characteristics {
// 6
for i in 0..<cUUIDs.count {
if let characteristicIndex = characteristics.index(where : {$0.uuid == cUUIDs[i]}) {
let characteristic = characteristics[characteristicIndex]
// 7
if !characteristic.isNotifying {
peripheral.setNotifyValue(true, for: characteristic)
} else {
peripheral.readValue(for: characteristic)
}
} else {
// 8
peripheral.discoverCharacteristics(characteristicUUIDs, for: ANDService)
}
}
}
} else {
// 5
peripheral.discoverServices([serviceUUID])
}
}
我试图测试它的方法是通过调用: -
kill(getpid(), SIGKILL);
模拟系统杀死进程。我不是在摆弄蓝牙状态/飞机模式或手机重启。 我在didLaunchWithOptions中初始化我的centralManager 我在didLaunchWithOptions上有断点,每次BP袖带准备好连接时都会调用断点,而且永远不会调用willRestoreState。
有人可以建议我还可以做些什么来调用willRestoreState?
答案 0 :(得分:0)
您需要在CBCentralManager中添加恢复ID,否则将永远不会调用委托方法。
let options = [CBCentralManagerOptionRestoreIdentifierKey: "my-central"]
self.centralManager = CBCentralManager(delegate: self, queue: nil, options: options)
完成此操作后,将在实例化CBCentralManager时始终调用willRestoreState。
还要确保在Info.plist中有一个带有“ bluetooth-central”项的UIBackgroundModes(数组)