如何在后台扫描BLE设备?

时间:2019-09-12 09:51:27

标签: ios swift bluetooth-lowenergy scanning

我想像扫描前景一样在后台扫描BLE设备。但是我的iOS应用程序无法正常运行。下面是我的AppDelegate类代码。

private var centralManager : CBCentralManager!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)return true
}

func applicationWillEnterForeground(_ application: UIApplication) {

    print("entering foreground...")
}

func applicationDidEnterBackground(_ application: UIApplication) {
    print("entered background...")

    print(centralManager.state)
    centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
}


func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        print("Bluetooth is On")
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    } else {
        print(central.state)
    }
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    print("\nName   : \(peripheral.name ?? "(No name)")")
    print("RSSI   : \(RSSI)")

    let name = peripheral.name ?? ""
    if name.contains("ETGuardian") {

        let DetailData = advertisementData["kCBAdvDataManufacturerData"]
        let DiscoveredData = String(describing: DetailData)

        print(DiscoveredData)

        for ad in advertisementData {
            print("AD Data: \(ad)")
        }
    }

  }
}

请帮助我像前台一样在后台状态下扫描应用程序。

1 个答案:

答案 0 :(得分:3)

来自文档:link

  

已指定蓝牙中央背景模式的应用为   允许在后台扫描。也就是说,他们必须   通过在中指定服务来显式扫描一个或多个服务   serviceUUIDs参数。 CBCentralManager扫描选项被忽略   在后台扫描时。

要使后台扫描正常工作,您需要指定serviceUUID。