后台监听特定的蓝牙特征值

Listen to specific Bluetooth characteristic value in backgeound

我知道使用 iBeacon 我可以在应用程序关闭时收听一些 UUID。 我想在应用程序关闭时收听 characteristic 的特定值。

因此,当应用 打开 并连接到设备时,我会在新数据到达时收到此委托:

  func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

           if characteristic.uuid.uuidString == characteristicUUID {

             if let str = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)

有没有办法在应用程序关闭时获取此委托?这样我就可以检查并看到我得到了我正在等待的正确字符串?

我知道我通常只有连接到设备才能听这个,但即使不连接我也想听。

当应用程序关闭时,iBeacon 是与任何 BLE 交互的唯一方式吗? 它非常有限。

我回答我的问题也是为了获得这些信息。(也感谢保罗)

所以今天为了能够在应用程序完全关闭(由用户或系统)时从硬件获取信息,您只能使用 iBeacons .

但 iBeacon 非常有限,您只能收听一些 UUID/MJ/MN 仅此而已。

如果想一直获取传感器数据怎么办?

Apple 采取的方法是,您应该始终与您的设备保持连接。因此,当您的应用程序处于后台时,当 characteristic 更新其值并且您仍然处于连接状态时,您只需获得相同的 delegates

出去了怎么办?

连接丢失,您要求重新搜索设备,当您回到家时,您有连接,您可以再次自动收听。

如果系统取消您的应用程序以释放内存怎么办?

在这种情况下,您使用 Preservation and Restoration,当应用 再次检测到硬件 时,它将恢复您的 CBCentral。为此:

centralManager=CBCentralManager(delegate: self, queue: nil, options: ["key":CBCentralManagerOptionRestoreIdentifierKey])

您在这里设置了 CBCentralManagerOptionRestoreIdentifierKey 和 "key"。 当 iOS 再次检测到信号时,您将获得此委托:

func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
    print(dict)
}

使用您的对象列表,您可以再次获取连接和数据。

底线: 方法是 - 如果您不断需要传感器数据,例如打开和关闭锁,您可以一直保持连接。(而不是使用 iBeacon)

另一个底线: 如果用户关闭了您的应用程序,正如 Paul 在此处所说,您将无法真正继续聆听,我认为这是一种非常奇怪的方法。

https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html