Swift 中的 BLE 后台扫描
Background Scanning for BLE in Swift
我正在尝试让我的应用程序在后台扫描 BLE 设备并在 Swift 中搜索一些广告数据。我一直无法在这里找到涵盖此内容的任何教程或问题。
基本上,当应用程序不在前台并且用户重新启动 phone 时,有没有办法在后台自动执行此操作?:
Obtaining Bluetooth LE scan response data with iOS
希望您能为我指明正确的方向。谢谢
第 1 步:为您的项目功能启用蓝牙后台模式
第 2 步:确保将适当的内容添加到您的 info.plist 文件
这里是 plist 代码,如果它没有添加的话:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>bluetooth-central</string>
</array>
然后,当您在 CBCentralmanager 上调用 "scanForPeripheralsWithServices" 时,您必须指定一组要扫描的服务。您不能将空数组传递给它。如果你传递 nil,它仍然会扫描,只是不在后台。
所以像这样指定一组服务 UUID:
let arrayOfServices: [CBUUID] = [CBUUID(string: "8888")]
self.myBluetoothManager?.scanForPeripheralsWithServices(arrayOfServices, options: nil)
现在,如果您关心选项,您可以传递一个选项字典来代替我上面传递的 nil。大多数情况下,这用于指定是否要在连接之前连续查看设备 RSSI,或者是否只需要一次广告数据包。放一个:
println(advertisementData["kCBAdvDataLocalName"] as! String)
println(advertisementData["kCBAdvDataManufacturerData"] as! NSData)
在 "didDiscoverPeripheral" 委托方法中观察不同的行为。
如果您想要重复键,这是您将传递的词典:
let dictionaryOfOptions = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
self.myBluetoothManager?.scanForPeripheralsWithServices(arrayOfServices, options: dictionaryOfOptions)
现在 Apple says that when your app goes in the background mode 它将此扫描选项默认为 false 但从 iOS 8.3 开始,我看到它一直在使用重复键进行扫描。
关于后台执行的最后一点说明。如果 iOS 决定暂停您的应用程序,扫描将停止。如果有一堆应用程序 运行.
,我已经看到这种情况只要 30 秒就会发生
我正在尝试让我的应用程序在后台扫描 BLE 设备并在 Swift 中搜索一些广告数据。我一直无法在这里找到涵盖此内容的任何教程或问题。
基本上,当应用程序不在前台并且用户重新启动 phone 时,有没有办法在后台自动执行此操作?: Obtaining Bluetooth LE scan response data with iOS
希望您能为我指明正确的方向。谢谢
第 1 步:为您的项目功能启用蓝牙后台模式
第 2 步:确保将适当的内容添加到您的 info.plist 文件
这里是 plist 代码,如果它没有添加的话:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>bluetooth-central</string>
</array>
然后,当您在 CBCentralmanager 上调用 "scanForPeripheralsWithServices" 时,您必须指定一组要扫描的服务。您不能将空数组传递给它。如果你传递 nil,它仍然会扫描,只是不在后台。
所以像这样指定一组服务 UUID:
let arrayOfServices: [CBUUID] = [CBUUID(string: "8888")]
self.myBluetoothManager?.scanForPeripheralsWithServices(arrayOfServices, options: nil)
现在,如果您关心选项,您可以传递一个选项字典来代替我上面传递的 nil。大多数情况下,这用于指定是否要在连接之前连续查看设备 RSSI,或者是否只需要一次广告数据包。放一个:
println(advertisementData["kCBAdvDataLocalName"] as! String)
println(advertisementData["kCBAdvDataManufacturerData"] as! NSData)
在 "didDiscoverPeripheral" 委托方法中观察不同的行为。
如果您想要重复键,这是您将传递的词典:
let dictionaryOfOptions = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
self.myBluetoothManager?.scanForPeripheralsWithServices(arrayOfServices, options: dictionaryOfOptions)
现在 Apple says that when your app goes in the background mode 它将此扫描选项默认为 false 但从 iOS 8.3 开始,我看到它一直在使用重复键进行扫描。
关于后台执行的最后一点说明。如果 iOS 决定暂停您的应用程序,扫描将停止。如果有一堆应用程序 运行.
,我已经看到这种情况只要 30 秒就会发生