iOS蓝牙连接报错总结

一、[CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral , Did you forget to keep a reference to it?

在蓝牙连接的时候总是报这个错误,这个看英文意思就可以理解,其实字面意思就是让我们把这个蓝牙对象给保存起来,就这么简单!

func centralManager(_ central: CBCentralManager,
                        didDiscover peripheral: CBPeripheral,
                        advertisementData: [String: Any],
                        rssi RSSI: NSNumber) {}
或
centralManager.retrievePeripherals(withIdentifiers: [bleUUID])

在搜索到设备的回调中 或者 重新获取已发现的设备列表,将需要连接的设备保存到数组中即可!

二、CBCentralManagerScanOptionAllowDuplicatesKey

let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: false)]
centralManager?.scanForPeripherals(withServices: nil, options: options)

由于苹果的限制,APP在后台运行时是扫描不到任何信息的;如果想在后台扫描蓝牙设备,必须指定扫描的设备serviceId;

let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: true)]
guard let bleUUID = UUID(uuidString: "指定的serviceUUID") else {     return  }
let cbUUID = CBUUID(nsuuid: bleUUID)
centralManager?.scanForPeripherals(withServices: cbUUID, options: options)

后台运行时必须勾选
TARGET→Capabilities→Background Modes→Uses Bluetooth LE accessories(勾选)

你可能感兴趣的:(蓝牙,蓝牙)