【发布时间】:2018-10-01 14:03:30
【问题描述】:
我正在尝试创建一个连接到 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 吗?
【问题讨论】:
-
您是否使用恢复 ID 实例化您的 CBCentralManager?
标签: bluetooth-lowenergy core-bluetooth cbcentralmanager ios-bluetooth state-restoration