ios - 当应用程序在后台时,如何在广告数据更改时获得通知?
问题描述
我想在 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)")
}
}
}
解决方案
为了让应用程序可以在后台运行,您需要在应用程序中实现一些后台服务。
通常,后台服务是位置获取。请注意,后台服务将使您的应用更快地耗尽电池电量
要实现后台服务,请单击您的项目、签名和功能、后台模式,启用 BLE 功能。
推荐阅读
- android - 错误:内部错误,无法使用 Gradle 分发执行构建
- google-cloud-platform - 谷歌语音 API 单一话语
- c - 如果 C 代码比较不同的数据类型,如何获得警告?
- python - 如何在 Odoo 10 中以编辑模式打开现有记录?
- java - 请帮助在 Java 中的 String.split() 方法中转义 NPE 错误
- php - 使用 select sum case 获取输出
- dependency-injection - Typo3 在 null 上调用成员函数
- javascript - 闭包的外部和内部函数中的相同变量
- sql - 在水晶报表中抑制字段的条件
- qt - 如何使用 v3 rest api 从谷歌驱动器下载文件?