首页 > 解决方案 > 当应用程序在后台时,如何在广告数据更改时获得通知?

问题描述

我想在 BLE 设备发生某些事情时得到通知。如果 BLE 设备将一些数据/命令传递给应用程序,则应用程序内的广告数据不会更改。但是我们可以用 android 做同样的事情,它工作得很好。我想实现功能,比如当广告数据发生变化时我想得到通知。请帮我实现这一点。下面是我的 AppDelegate.swift 类。

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...")

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


func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        print("Bluetooth is On")

        let kTrackStandardDeviceInfoServiceUUID  = CBUUID(string: "180A")

        let dictionaryOfOptions = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
        let arrayOfServices: [CBUUID] = [kTrackStandardDeviceInfoServiceUUID]

        centralManager.scanForPeripherals(withServices: arrayOfServices, options: dictionaryOfOptions)
    } 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)")
        }
    }
}

标签: iosswiftbluetooth-lowenergycbperipheralcbperipheralmanager

解决方案


为了让应用程序可以在后台运行,您需要在应用程序中实现一些后台服务。

通常,后台服务是位置获取。请注意,后台服务将使您的应用更快地耗尽电池电量

要实现后台服务,请单击您的项目、签名和功能、后台模式,启用 BLE 功能。


推荐阅读