I am trying to connect to a MacBook Pro from an iPad with CoreBluetooth.
Here is my delegation for 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?) {}
}
But when I scan I get this error in the log:
<Error>: [CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral
Why does this happen?
Not sure why this worked, but I found that it works if I assign the peripherals delegate to self, and add the peripheral to an array before I connect to it.
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)
}