我想制作可以在后台模式下工作的BLE扫描仪。
首先,我通过以下代码发现了外围设备及其服务uuid。
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
central.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
default:
central.stopScan()
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
self.scannedPeripherals.appendAsUnique(peripheral)
central.connect(peripheral)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
peripheral.delegate = nil
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
peripheral.services?.forEach {
peripheral.discoverCharacteristics([$0.uuid], for: $0)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
// I got a service uuid here!
print(service.uuid)
}
此代码使我可以在前台模式下执行所有操作。
因此,我了解了现在可以扫描的服务uuid,包括180A (Device Information)
,180F (Battery Service)
,1805 (Current Time Service)
,D0611E78-BBB4-4591-A5F8-487910AE4366 (Continuity)
,9FA480E0-4967-4542-9390-D343DC5D04AE
。
我已经看到文档(例如Background Scanning for BLE in Swift)说我需要添加服务uuid而不是withServices: nil
才能在后台模式下工作,所以我添加了我所知道的服务uuid下面的代码。
central.scanForPeripherals(withServices: [CBUUID(string: "180A")], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
central.scanForPeripherals(withServices: [CBUUID(string: "180F"), CBUUID(string: "9FA480E0-4967-4542-9390-D343DC5D04AE")])
但是,此后没有发现任何外围设备。 (即使在前台模式下也是如此。)
全部扫描=> 180A
服务已扫描
使用180A
服务进行扫描=>未扫描任何内容
怎么了? :'(
ps。谢谢Paulw11。