蓝牙LE后台扫描

时间:2020-03-15 02:23:50

标签: ios swift bluetooth-lowenergy

我正在制作一个有关在后台模式下扫描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 个答案:

答案 0 :(得分:1)

您要执行的操作遇到了两个问题:

  1. Timer不会在您的应用暂停时触发;在iOS上不受支持的后台模式具有特定时间段的执行。
  2. 在后台扫描时不能使用CBCentralManagerScanOptionAllowDuplicatesKey

由于您已在Info.plist中选择了蓝牙后台​​模式,假设用户已授予蓝牙后台许可,则每次新设备时,您都会收到didDiscover委托回调。可以看到正在宣传指定的服务(DEC18772-CCC0-462D-92FB-F5C823537895)。

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

当您的应用程序仍在后台运行时,您将不会再收到该设备的其他委托发现回调。