【发布时间】:2020-11-04 08:16:47
【问题描述】:
我正在尝试与蓝牙激光标签枪进行通信,该枪以 20 字节块的形式获取数据,这些块被分解为 16、8 或 4 位字。为此,我创建了一个 UInt8 数组并更改了其中的值。当我尝试发送 UInt8 数组时会出现问题。
var bytes = [UInt8](repeating: 0, count: 20)
bytes[0] = commandID
if commandID == 240 {
commandID = 0
}
commandID += commandIDIncrement
print(commandID)
bytes[2] = 128
bytes[4] = UInt8(gunIDSlider.value)
print("Response: \(laserTagGun.writeValue(bytes, for: gunCControl, type: CBCharacteristicWriteType.withResponse))")
commandID 只是一个 UInt8。这给了我错误,Cannot convert value of type '[UInt8]' to expected argument type 'Data',我试图通过这样做来解决:
var bytes = [UInt8](repeating: 0, count: 20)
bytes[0] = commandID
if commandID == 240 {
commandID = 0
}
commandID += commandIDIncrement
print(commandID)
bytes[2] = 128
bytes[4] = UInt8(gunIDSlider.value)
print("bytes: \(bytes)")
assert(bytes.count * MemoryLayout<UInt8>.stride >= MemoryLayout<Data>.size)
let data1 = UnsafeRawPointer(bytes).assumingMemoryBound(to: Data.self).pointee
print("data1: \(data1)")
print("Response: \(laserTagGun.writeValue(data1, for: gunCControl, type: CBCharacteristicWriteType.withResponse))")
对此,data1 只打印0 bytes,我可以看到laserTagGun.writeValue 实际上并没有通过从其他特征读取数据来做任何事情。如何快速将我的 UInt8 数组转换为 Data?另外请让我知道是否有比 UInt8 数组更好的方法来处理 20 字节的数据。感谢您的帮助!
【问题讨论】:
-
你想避免复制吗?
标签: ios arrays swift bluetooth binary