我的应用可以在前台连接到BLE设备。但是,当应用程序处于后台时,BLE设备在断开设备后不会再次重新连接。我在info.plist中添加了所需的权限:
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>bluetooth-peripheral</string>
</array>
我在HomeViewController中创建了用于扫描的中央管理器对象:
let centralManager = CBCentralManager(delegate: self, queue: nil)
centralManager.delegate = self
let options = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
centralManager.scanForPeripherals(withServices:nil, options: options)
我在后台使用app时尝试使用服务的scanForPeripherals但它不起作用:
let backgroundScanOptions = [CBCentralManagerScanOptionSolicitedServiceUUIDsKey : true]
centralManager.scanForPeripherals(withServices: [customServiceUUIDs], options: backgroundScanOptions)
如何在后台重新连接设备?
答案 0 :(得分:0)
swift 4
import UIKit
import CoreBluetooth
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CBCentralManagerDelegate, CBPeripheralDelegate{
var window: UIWindow?
//MARK:- all variables...
var bleCentralManager: CBCentralManager!
var selectedPeripheral: CBPeripheral!
let serviceUUIDForBackgroundScanning: [CBUUID] = [CBUUID(string: "07A2715C-3B28-4F7F-8824-BA18255B2344")
func bleCentralManagerfunc(){
self.bleCentralManager = CBCentralManager(delegate: self, queue: nil)
}
//MARK:- CBCentralManagerDelegate methods...
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state{
case .poweredOn: central.scanForPeripherals(withServices: nil, options: nil)
default: print("Please turn on Bluetooth")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if !(self.arrayPeripheralList.contains(peripheral)){
self.arrayPeripheralList.append(peripheral)
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
self.bleCentralManager.scanForPeripherals(withServices: serviceUUIDForBackgroundScanning, options: nil)
}
}