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

时间:2016-10-18 16:31:25

标签: ios swift core-bluetooth cbperipheralmanager

我正在尝试使用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

为什么会这样?

2 个答案:

答案 0 :(得分:4)

不确定为什么会这样,但是我发现如果我将外设委托分配给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 :(得分:0)

我看到了这个错误,对于那些也面临同样问题的人,我的建议是我没有将 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