我有一个包含CBPeripheral
数组的单例类。发现新设备时,会将其添加到该阵列。此数组用作UITableView
数据源。当用户选择表格视图单元格时,将通过提取连接到所选的CBPeripheral
。
不幸的是我收到了这个错误:
[CoreBluetooth] API MISUSE:取消未使用的外围设备
<CBPeripheral: 0x1c0103e70, identifier = xxx, name = xxx, state = connecting>
的连接,您是否忘记保留对它的引用?
我搜索了堆栈溢出,之前有过类似的问题,但是所有人都说根本原因是&#34;没有添加外设到强引用,所以iOS释放它&#34;。但我已将它们添加到数组中。
代码:
class BLEManager:NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
static let sharedInstance = BLEManager()
var centralManager: CBCentralManager!
var connectedService: BLEDSPService?
var delegate: BLEDiscoveryDelegate?
var readUUIDString: String
var writeUUIDString: String
var serviceUUIDString: String
var connectedPeripheral: CBPeripheral?
var peripherals = [CBPeripheral]() {
didSet {
delegate?.peripheralDidDiscoverNewOnes()
}
}
init(serviceUUIDString: String, readUUIDString: String, writeUUIDString: String) {
self.readUUIDString = readUUIDString
self.writeUUIDString = writeUUIDString
self.serviceUUIDString = serviceUUIDString
super.init()
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main);
}
internal func startScanning() {
let serviceUUID = CBUUID(string: serviceUUIDString)
let options = [CBCentralManagerScanOptionAllowDuplicatesKey: 0]
centralManager.scanForPeripherals(withServices: [serviceUUID], options: options)
}
func stopScanning() {
centralManager.stopScan()
delegate?.peripheralDidStopScan()
}
open func connectTo(index: Int) {
if let current = connectedPeripheral {
disconnectPeripheral(current)
}
if index < peripherals.count {
connectPeripheral(peripherals[index])
stopScan()
}
}
@objc func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard let name = peripheral.name?.lowercased() else {
return
}
guard (name.contains(NamesManager.shared.scanName)) else {
return
}
if !peripherals.contains(peripheral) {
peripherals.append(peripheral)
delegate?.peripheralDidDiscovered()
}
}
但是如果我将外设保存到var,那么连接它。它有效:
var connectedPeripheral: CBPeripheral?
open func connectTo(index: Int) {
if let current = connectedPeripheral {
connectPeripheral(current)
}
stopScan()
}
@objc func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard let name = peripheral.name?.lowercased() else {
return
}
guard (name.contains(NamesManager.shared.scanName)) else {
return
}
if !peripherals.contains(peripheral) {
connectedPeripheral = peripheral
peripherals.append(peripheral)
stopScanning()
delegate?.peripheralDidDiscovered()
}
}