我正在尝试在后台连接BLE,但它没有在后台连接。 当我的应用程序在前台时它正在工作。 我正在尝试使用外设的UUID进行扫描。 这是附加的代码。
override func viewDidLoad() {
super.viewDidLoad()
manager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
var msg = ""
switch central.state {
case .poweredOff:
msg = "Bluetooth is Off"
case .poweredOn:
msg = "Bluetooth is On"
let arrayOfServices: [CBUUID] = [CBUUID(string: "CCAExxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")]
manager?.scanForPeripherals(withServices:arrayOfServices, options: nil)
case .unsupported:
msg = "Not Supported"
default:
msg = "Not Connected"
}
print("STATE: " + msg)
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("Name: \(peripheral.name)") //print the names of all peripherals connected.
//you are going to use the name here down here ⇩
if peripheral.name == "Name of device" { //if is it my peripheral, then connect
self.myBluetoothPeripheral = peripheral //save peripheral
self.myBluetoothPeripheral.delegate = self
manager.stopScan() //stop scanning for peripherals
manager.connect(myBluetoothPeripheral, options: nil) //connect to my peripheral
}
}
如何解决?
答案 0 :(得分:0)
您需要做的是在实例化CentralManager时需要使用恢复标识符对其进行实例化。
例如:
CBCentralManager(delegate: self,options:
[CBCentralManagerOptionRestoreIdentifierKey: "bleCentralManager"])
这是必要的,因为它说的苹果文档"核心蓝牙只保留那些具有恢复标识符的对象的状态"。
然后,当您的应用重新启动到后台时,您必须在appDelegate的应用程序中使用相同的恢复标识符重新实例化相应的中央管理器:didFinishLaunchingWithOptions:method。您可以获得这样的恢复标识符:
let centralManagerIdentifiers = launchOptions![UIApplicationLaunchOptionsKey.bluetoothCentrals]
最后在您的中央管理器centralManager(_ central:CBCentralManager,willRestoreState dict:[String:Any])委托方法中,您可以获得中央管理器连接或尝试连接并执行任何操作的所有外围设备的列表想用这种方法做。
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey]
}
答案 1 :(得分:0)