在扫描设备时选择特定服务
我做了一个程序,我想用特定的服务来扫描一个设备(我的设备是一个温度计 "SHT31",服务是电池服务 "UUID: 180F"),但是当我在iPhone上运行这个程序时,它并没有扫描设备。而当 "withServices: nil "时,它会扫描设备。你有解决办法吗?
我的代码:
import CoreBluetooth
class BLEConnection: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var myPeripheral: CBPeripheral!
let batteryServiceCBUUID = CBUUID(string: "0x180F")
func startCentralManager() {
self.centralManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch (central.state) {
case .unsupported:
print("BLE is Unsupported")
break
case .unauthorized:
print("BLE is Unauthorized")
break
case .unknown:
print("BLE is Unknown")
break
case .resetting:
print("BLE is Resetting")
break
case .poweredOff:
print("BLE is Powered Off")
break
case .poweredOn:
print("BLE powered on")
central.scanForPeripherals(withServices: [batteryServiceCBUUID], options: nil)
break
@unknown default:
break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let pname = peripheral.name {
// print(pname)
if pname == "Smart Humigadget" {
self.centralManager.stopScan()
self.myPeripheral = peripheral
self.myPeripheral.delegate = self
self.centralManager.connect(peripheral, options: nil)
print("\(pname) is connected")
}
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.myPeripheral.delegate = self
self.myPeripheral.discoverServices(nil)
}
}
使用以下格式(不需要十六进制前缀)。
let batteryServiceCBUUID = CBUUID(string: "180F")