[英]Re-Connect BLE device in background iOS
My app can connect in foreground to BLE devices. 我的应用程序可以在前台连接到BLE设备。 But BLE device doesn't re-connect again after disconnect device while the app is in background.
但是当应用程序在后台运行时,断开设备连接后,BLE设备不会再次重新连接。 I added required permission in info.plist :
我在info.plist中添加了所需的权限:
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>bluetooth-peripheral</string>
</array>
I created central manager object for scanning in HomeViewController : 我创建了要在HomeViewController中进行扫描的中央管理器对象:
let centralManager = CBCentralManager(delegate: self, queue: nil)
centralManager.delegate = self
let options = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
centralManager.scanForPeripherals(withServices:nil, options: options)
I tried scanForPeripherals with services when app in background but it doesn't work : 我在后台运行应用程序时尝试了带有服务的scanForPeripherals,但是它不起作用:
let backgroundScanOptions = [CBCentralManagerScanOptionSolicitedServiceUUIDsKey : true]
centralManager.scanForPeripherals(withServices: [customServiceUUIDs], options: backgroundScanOptions)
What can I do for re-connect device in background ? 在后台重新连接设备该怎么办?
swift 4 迅捷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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.