我遇到了
Xcode 9.2和iOS 11.1.2的问题,“diddiscover”工作正常,我的外设在我调用connect之前保存在一个数组中,但是没有调用“didConnect”或“didFailToConnect”,所以外围状态将保持不变在“连接”…
请帮忙
请帮忙
var manager: CBCentralManager! override func viewDidLoad() { super.viewDidLoad() manager = CBCentralManager(delegate: self,queue: nil) //manager = CBCentralManager (delegate: self,queue: dispatchQueue.main) //manager = CBCentralManager.init(delegate: self,queue: nil,options:[:]) //manager.delegate = self } func centralManager(_ central: CBCentralManager,diddiscover peripheral: CBPeripheral,advertisementData: [String : Any],RSSi RSSI: NSNumber) { guard let name = peripheral.name else { return } print("BR peripheral.name = \(name),RSSi = \(RSSI),adertisementData = \(advertisementData)") if (peripheral.name?.hasPrefix("testBT"))! { peripheralArray.append(peripheral) manager.connect(peripheralArray.first!,options: [:]) print("Connecting to peripheral \(peripheral)") } } func centralManager(_ central: CBCentralManager,didConnect peripheral: CBPeripheral) { print("BT connected!") manager.stopScan() peripheral.delegate = self peripheral.discoverServices(nil) } func centralManager(_ central: CBCentralManager,diddisconnectPeripheral peripheral: CBPeripheral,error: Error?) { print("BT disconnected!") } func centralManager(_ central: CBCentralManager,didFailToConnect peripheral: CBPeripheral,error: Error?) { print("BT Failed!") }
解决方法
尝试使变量全局:
var myPeripheral:CBPeripheral?
比,在你的代码编辑它:
if (peripheral.name?.hasPrefix("testBT"))! { myPeripheral = peripheral //HERE WRITE DELEGATE,NOT IN didConnect myPeripheral!.delegate = self //peripheralArray.append(myPeripheral) manager.connect(myPeripheral!,options: nil) print("Connecting to peripheral \(peripheral)") }
现在我认为它应该有效.我也会开始扫描centralManagerDidUpdateState以确保蓝牙正常工作,如:
func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state{ case .poweredOn: startScan() // own method where i start scanning case .poweredOff: print("blth powered off") case .unsupported: print("bltyh noit supported") } }
等等还有更多状态,您可以在文档中查看.在vievDidLoad中初始化你的CBCentralManager var(manager = CBCentralManager(delegate:self,queue:nil))后调用centralManagerDidUpdateState方法
希望能帮助到你
顺便说一句,你正在制作一个阵列来存储连接的外围设备.请记住,无论何时从存储该阵列的控制器返回并返回该阵列,该阵列将再次为空.这就是为什么如果你需要你的蓝牙课程全球工作,我建议你制作一个可以实现Singleton的BluetoothService课程,你可以访问你项目中任何地方的任何状态