由于 API 误用,CoreBluetooth 正在与未使用的外围设备断开连接

CoreBluetooth is disconnecting from unused peripherals due to an API Misuse

我正在尝试使用 CoreBluetooth 从 iPad 连接到 MacBook Pro。

这是我的 CBCentralManagerDelegate 代表团:

extension MasterViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            print("Scanning for peripherals")
            central.scanForPeripherals(withServices: nil, options: nil)
            Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.stopScan), userInfo: nil, repeats: true)
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("Did discover peripheral", peripheral)

        central.connect(peripheral, options: nil)

    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Did connect to ", peripheral)

        peripheral.delegate = self
        self.remotePeripheral.append(peripheral)
    }

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {}
}

但是当我扫描时,我在日志中收到此错误:

<Error>: [CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral

为什么会这样?

不确定为什么会这样,但我发现如果我将外围设备委托分配给自己,并将外围设备添加到数组我连接到它之前它会起作用。

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    print("Did discover peripheral", peripheral)

    peripheral.delegate = self
    self.remotePeripheral.append(peripheral)

    central.connect(peripheral, options: nil)

}

我看到了这个错误,对于那些也面临同样问题的人,我的建议是我没有将 CBPeripheral 设备存储在我的助手 class 中。这似乎没有必要,但出于某种原因,我相信它需要在内部进行限制。 好吧,这就是我所做的:-

    class BLEHelper: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate{
        
    @Published var pairedDevice:CBPeripheral?=nil
    ...

然后在您的 didDiscover 函数中:

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
pairedDevice=peripheral
peripheral.delegate=self
myCentral.connect(peripheral, options:nil)
myCentral.stopScan()

}

这里的这一行起到了作用:- pairedDevice=peripheral