繁体   English   中英

在后台iOS中重新连接BLE设备

[英]Re-Connect BLE device in background iOS

我的应用程序可以在前台连接到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)

在后台重新连接设备该怎么办?

迅捷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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM