Ios 由于API误用,CoreBluetooth正在断开与未使用的外围设备的连接
我正在尝试从带有CoreBooth的iPad连接到MacBook Pro 这是我对CBCentralManagerDelegate的代表团:Ios 由于API误用,CoreBluetooth正在断开与未使用的外围设备的连接,ios,swift,core-bluetooth,cbperipheralmanager,Ios,Swift,Core Bluetooth,Cbperipheralmanager,我正在尝试从带有CoreBooth的iPad连接到MacBook Pro 这是我对CBCentralManagerDelegate的代表团: extension MasterViewController: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn {
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
:[CoreBluetooth]API误用:取消未使用外设的连接
为什么会发生这种情况?不确定为什么会发生这种情况,但我发现,如果我将外围设备委托给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)
}
我看到了这个错误,对于那些同样面临同样问题的人,我的建议是我没有将
cbperipal
设备存储在我的helper类中。这似乎是不必要的,但出于某种原因,我认为这需要在内部加以限制。
好吧,我是这么做的:-
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
您需要保留对CBPeripheral的引用,否则它们将被释放。这不是关于“委托销售”,而是关于self.remoteperipal.append(peripheral)
。我要补充的是,这里有更多的解释:(在Objective-C中,但情况是一样的:CoreBlutooth没有保留参数的强引用,因此它们可能会很快发布)在8小时的调试后救了我一命,搜索SO+尝试和错误!谢谢