我已将CoreBluetooth设置在我的应用程序中作为Central,实现了CBCentralManagerDelegate以使用我的服务扫描外围设备。我还在bluetooth-central
文件中声明了Info.plist
后台模式。
连接后,我会发现服务并阅读我需要的任何特征。当在外围设备侧修改或添加服务时,我会响应外围设备:didModifyServices:方法,并重新发现服务,这在前台工作正常。
我的问题是,当我的应用程序在后台,并且我连接的外围设备添加服务时,不会调用外围设备:didModifyServices:方法。但是,当我的Central应用程序在后台时,不会调用该方法。当我的应用程序在后台时,会收到其他CBPeripheralDelegate方法(外围设备:didDiscoverServices:,外围设备:didDiscoverCharacteristicsForService:错误:等)。
此行为对bluetooth-central
后台模式是否正确?
代码如下:
CBCentralManagerDelegate:
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
central.scanForPeripherals(withServices: [primaryService], options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
print("Discovered peripheral " + name)
peripheral.delegate = self
connectedPeripherals.insert(peripheral)
central.connect(peripheral, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
connectedPeripherals.remove(peripheral)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
connectedPeripherals.remove(peripheral)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
CBPeripheralDelegate:
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services ?? [] {
if isRecognizedService(service) {
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
print("Peripheral services changed...")
peripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("Error discovering characteristics...")
return
}
guard let characteristics = service.characteristics, !characteristics.isEmpty else {
print("No characteristics found for service...")
return
}
for characteristic in service.characteristics ?? [] {
// Subscribe to characteristic changes, etc...
}
}