Apple iOS Swift5 BLE - 如何向特征发送 1 个字节(写入函数需要数据类型,但一个字节是 "UInt8" 类型)

Apple iOS Swift5 BLE - How to send 1 byte to a characteristic (write function expects Data type, but one byte is "UInt8" type)

我正在开发将浮点数和 8、16、32 位整数数据类型写入现有 BLE GATT 外围设备的代码。外围特性是为这些特定尺寸构建的。对于 Floats 和 32 位 Ints,创建 Data 类型往往会在缓冲区中创建无关的 0,并使其成为 5 字节对象,我的外围设备拒绝这样做。所以我这样切片:

let int32Value = Int32(fieldValue)
let data = withUnsafeBytes(of: int32Value) { Data([=12=]) }
let data_slice = data[0...3]
peripheral.writeValue(data_slice, for: characteristic, type: writeType)

对于 16 位整数,我只是以不同的方式对其进行切片:

let int16Value = Int16(fieldValue)
let data = withUnsafeBytes(of: int16Value) { Data([=13=]) }
let data_slice = data[0...1]
peripheral.writeValue(data_slice, for: characteristic, type: writeType)

一切正常,我可以看到设备上已经设置了数据。但是对于 8 位整数,我尝试:

let int8Value = Int8(fieldValue)
let data = withUnsafeBytes(of: int8Value) { Data([=14=]) }
let data_slice = data[0]
peripheral.writeValue(data_slice, for: characteristic, type: writeType)

我得到一个编译时错误——writeValue 方法需要第一个参数是 Data 类型,但是从上面的代码来看,它将 data_slice 解释为 Bytes 对象,不会编译。如果我不执行“data_slice”操作,那么 data 的长度为 2 个字节,这是我在这里创建它的方式,并被我的外围设备拒绝。我收到“不正确的特征数据长度”错误。

我好像在第二十二条军规中。我需要用来发送 BLE 外设值的系统级 writeValue 函数不允许将单个 8 位 Int 作为参数。但是我的外围设备上的特征不会接受任何东西。发送单个 8 位 Int 在 Android 等其他平台上对我有用。遇到这种情况怎么办?

显示 Int8 和 Int32 案例的图像:

问题是您的 Int8 是可选的。这就是为什么你得到一个额外的字节。您需要做的就是在将可选数据转换为数据之前解包它。