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

问题描述 投票:0回答:3

我正在尝试通过 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

为什么会出现这种情况?

ios swift core-bluetooth cbperipheralmanager
3个回答
5
投票

不知道为什么这会起作用,但我发现如果我将外围设备委托分配给 self,并将外围设备添加到数组在连接到它之前,它就会起作用。

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)

}

1
投票

我看到了这个错误,对于那些也面临同样问题的人,我的建议是我没有将

CBPeripheral
设备存储在我的助手类中。这似乎没有必要,但出于某种原因,我认为它需要在内部受到限制。 好吧,这就是我所做的:-

    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


0
投票

我遇到了同样的错误,但是已经存储了对我的外围设备的引用。我意识到我有一个不同的 CBCentralManager 实例已经与另一个视图控制器关联,并且在完成后将未使用的实例设置为零,解决了警告。

© www.soinside.com 2019 - 2024. All rights reserved.