【问题标题】:How to read characteristics in background BLE using CoreBluetooth如何使用 CoreBluetooth 在后台 BLE 中读取特征
【发布时间】:2019-05-02 07:05:28
【问题描述】:

我正在开发在后台模式下读取特定特征的应用程序。这可以通过在 plist 中选择背景模式为"Uses Bluetooth LE Accessories" 在后台实现吗?如果我们读取已知服务的特定特征,是否有可能在后台拒绝应用程序?阅读特征应该不断发生。如果我们setNotify to "True" 将在后台工作。如果有人知道,请提供一些有价值的建议/解决方法。提前致谢。

【问题讨论】:

    标签: ios swift bluetooth-lowenergy core-bluetooth


    【解决方案1】:
    1. 这可以通过在 plist 中选择后台模式为“使用蓝牙 LE 附件”在后台实现吗?

    是的,当您的应用处于后台模式时,您绝对可以读取 ble 特性,在功能选项卡中设置“使用蓝牙 LE 附件”后台模式

    1. 如果我们读取已知服务的特定特征,是否有可能在后台拒绝应用?

    如果您的应用需要 ble 后台模式并在功能选项卡中正确声明,则该应用不会被拒绝

    1. 应该连续读取特征。如果我们将通知设置为“True”,这将在后台工作

    为了在每次 ble 外围设备的 ble 特性更改其值时得到通知,您可以正确地将所需特性上的 setNotify 设置为 true。每次特征更改其值时,都会触发peripheral(_:didUpdateStateFor:Error) 回调,您可以获得更新后的值。正确设置后台模式,即使您的应用处于后台且手机被锁定,也会触发此回调。

    【讨论】:

    • 它正在工作:) 我已经添加了代码并在我的设备中进行了测试。即使手机被锁定,值也会收到通知:D
    【解决方案2】:

    func 外围设备(_ 外围设备:CBPeripheral,didUpdateValueFor 特性:CBCharacteristic, 错误:错误?) {

        print("characteristic: ", characteristic)
    
        guard let string = String(bytes: characteristic.value!, encoding: .utf8) else {
            return
        }
    
    
    }
    

    【讨论】:

      【解决方案3】:
      【解决方案4】:
      func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService,
                          error: Error?) {
              guard let characteristics = service.characteristics else { return }
      
              for characteristic in characteristics {
                  print(characteristic)
                  if characteristic.properties.contains(.read) {
                      print("\(characteristic.uuid): properties contains .read")
      
                      peripheral.readValue(for: characteristic)
                  }
                  if characteristic.properties.contains(.notify) {
                      print("\(characteristic.uuid): properties contains .notify")
      
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2016-07-26
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多