【问题标题】:How to get notify when advertisementData changed when app is in background?当应用程序在后台时,如何在广告数据更改时获得通知?
【发布时间】:2020-01-14 23:13:06
【问题描述】:

我想在 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)")
        }
    }
}

【问题讨论】:

    标签: ios swift bluetooth-lowenergy cbperipheral cbperipheralmanager


    【解决方案1】:

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

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

    要实现后台服务,请点击您的项目、Signing & Capabilities、Background Modes,启用 BLE 功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多