我的应用程序可以在前台连接到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)我在后台的应用程序中尝试了scanForPeripherals,但是它不起作用:
let backgroundScanOptions = [CBCentralManagerScanOptionSolicitedServiceUUIDsKey : true]
centralManager.scanForPeripherals(withServices: [customServiceUUIDs], options: backgroundScanOptions)在后台我能为重新连接设备做些什么?
发布于 2017-11-21 10:47:07
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)
}
}https://stackoverflow.com/questions/47409097
复制相似问题