后台低功耗蓝牙扫描

Bluetooth LE scanning in background

我正在制作一个关于在 后台模式 下扫描 BLE 设备的应用程序,并每分钟将设备列表发送到服务器

private let uuid = CBUUID(string: "DEC18772-CCC0-462D-92FB-F5C823537895")

self.centralManager?.scanForPeripherals(withServices: [uuid], options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])

在 plist 文件中

    <array>
        <string>bluetooth-central</string>
        <string>bluetooth-peripheral</string>
    </array>

我使用计时器在 60 秒后将设备列表发送到服务器

var timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)

但是当我将应用程序设置为后台模式时,一切似乎都暂停了,定时器和 didDiscover 回调不起作用

是否缺少使应用程序 运行 处于后台模式的任何内容?

您尝试执行的操作遇到了一些问题:

  1. A Timer 在您的应用暂停时根本不会触发; iOS.
  2. 不支持特定时间段的执行
  3. 后台扫描时无法使用CBCentralManagerScanOptionAllowDuplicatesKey

由于您在 Info.plist 中选择了蓝牙后台​​模式,假设用户授予蓝牙后台权限,您将在每次 时收到一个 didDiscover 委托回调发现新设备 正在通告指定服务 (DEC18772-CCC0-462D-92FB-F5C823537895)。

您可以在此回调中向您的服务器报告发现此设备。

当您的应用保留在后台时,您将不会收到该设备的任何其他委托发现回调。