首页 > 解决方案 > .writeValue 不会让我将十六进制字符串写入特征以启用通知

问题描述

我的 ble 外围设备要求我将十六进制值 0x0001 写入我的 CCCD 描述符以启用通知。当我尝试使用 .notify 属性将值写入特征时,我收到以下错误:

Cannot invoke 'writeValue' with an argument list of type '(Data:String, for: CBCharacteristic)'

如何将值写入我的特征以便接收通知?

我试图删除 .writeValue 行并只保留 .setNotifyValue 行,但是当我从设备发送数据时,我没有收到通知。收到通知时是否必须读取该值?通知是否应该只将值写入我的输出?

  if characteristic.properties.contains(.notify) {
    print("\(characteristic.uuid): properties contains .notify")
    NUB5.writeValue(Data: "0x0001", for: characteristic)
    NUB5.setNotifyValue(true, for: characteristic)
  }

// BL652 需要将 0x0001 的值写入 TX CCCD 以通知我们数据。

标签: swiftxcodebluetooth-lowenergy

解决方案


  1. setNotifyValue(true, for: characteristic)应该足够了。你实现peripheral(_:didUpdateValueFor:error:)方法了吗?你能显示代码吗?

  2. writeValue接受Data输入,但您尝试通过String. 您需要对其进行编码,例如:

let encodedString = "Lorem ipsum".data(using: .utf8)

let number = 1
let encodedNumber = withUnsafeBytes(of: number) { Data($0) }

推荐阅读