SwiftUI-在蓝牙中扫描设备时选择特定服务

SwiftUI-在蓝牙中扫描设备时选择特定服务,swift,xcode,bluetooth-lowenergy,swiftui,core-bluetooth,Swift,Xcode,Bluetooth Lowenergy,Swiftui,Core Bluetooth,扫描设备时选择特定服务 我做了一个程序,我想用特定的服务扫描设备(我的设备是温度计“SHT31”,服务是电池服务“UUID:180F”),但当我在iPhone上运行这个程序时,它不会扫描设备。而当“withServices:nil”时,它会扫描设备。你有解决办法吗 我的代码: import CoreBluetooth class BLEConnection: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate { var

扫描设备时选择特定服务

我做了一个程序,我想用特定的服务扫描设备(我的设备是温度计“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)
    }
}
使用以下格式(不需要十六进制前缀)


我尝试了您建议的线路,但它仍然没有扫描设备。@MxM,这是正确的id声明,您确定您的设备准确地发布了此服务吗?我有一个包含设备详细信息的文件:“”。当“withServices:nil”时,它会扫描设备,但当我使用CBUUID(字符串:“180F”)或CBUUID(字符串:“180A”)时,它不会扫描设备。我觉得很奇怪。@MxM,也许这个设备没有电池服务的名称,如果让pname=peripheral.name,你就没有进入
{
条件。您是否尝试在回调的第一行设置断点或在开头添加打印日志?我认为我的设备不可能这样做,非常感谢您的帮助。
    let batteryServiceCBUUID = CBUUID(string: "180F")