记录iOS端在App进入后台以后的扫描蓝牙设备的表现

470 阅读1分钟

要开启Background Modes,并使用相对应的api进行初始化,否则app一进入后台就会停止扫描设备

  1. 在Capabilities中开启Backround Modes,勾选“Uses Bluetooth LE accessories”

  2. 在info.plist文件中添加

<key>UIBackgroundModes</key>
<array>
	<string>bluetooth-central</string>
</array>
  1. 使用支持后台扫描的初始化方法初始化CBCentralManager对象
let options = [CBCentralManagerOptionRestoreIdentifierKey: "a.sui"]
centralManager = CBCentralManager(delegate: self, queue: nil, options: options)
  1. 扫描的时候需要设置withServices参数,否则进入后台也是会停止扫描
centralManager.scanForPeripherals(withServices: [CBUUID(string: "ABCD")], options: [CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: true)])

观察app退到后台的扫描表现

  1. 进入后台前扫描到的设备似乎就不会出现在扫描的回调方法里。 在iPhone Xs(iOS 16.7.8)真机上测试多次的表现:进入后台以后,新通电的设备能够被扫描到,而进入后台之前扫描到的设备就不会再出现在回调方法里了

  2. 频次被降低了 在iPhone Xs(iOS 16.7.8)真机上测试多次的表现:入后台以后,虽然能够扫描到新通电的设备,但是扫描回调方法的频次明显下降了很多

iOS官方社区里技术客服的反馈:当扫描应用程序处于后台时,扫描速度会急剧减慢,因此即使您收到多个回调,也会丢失大量广告数据包。

参考

《ble 4.0后台运行介绍》

《iOS ble scan on background》