解決方案來源:
ShenYun's Memo: iOS CoreBluetooth swift 2 連線客製化藍芽 BLE 模組 - ( 2 ) 連線
swift - CoreBluetooth XPC connection invalid - Stack Overflow
解說
1: 專案的 Target -> Capabilities -> Background Modes -> 勾選兩個 Bluetooth LE Accessor
2: info.plist 要加上
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Play with BLE Compatible devices</string>
3: 把 CBCentralManager 放在一個 Class中
class TBleDeviceConnect: NSObject, CBCentralManagerDelegate, BPeripheralDelegate { var centralManager: CBCentralManager! = nil func centralManagerInit() { centralManager = CBCentralManager.init(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true]) } }
4: 把包含 CBCentralManager Class放到 MainViewController 中
CBCentralManager一定要在 UIViewController中
class MainViewController: UIViewController { /* Class Bluetooth CBCentralManager Control */ var BleDeviceConnect: TBleDeviceConnect! = nil }
5: 如果是用在其他的 ViewController
用 prepare for segue 方法將 CBCentralManager傳遞過去
請參考 iOS swift 5: About Segue Prepare to NavigationController
6: 如果是在 Thread Function 中使用
DispatchQueue.main.async { self.BleDeviceConnect.centralManagerInit() }
7: 同一個Class 中的CBCentralManager 只能呼叫一次 centralManager = CBCentralManager.init(...)
就會發生 "CoreBluetooth XPC connection invalid"
解決方法還在尋找中....
所以現在的做法呼叫 scanForPeripherals來重新掃描 Bluetooth Device
沒有留言:
張貼留言