gpt4 book ai didi

ios - swift3中的CB特征值

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:20:21 25 4
gpt4 key购买 nike

我是快速开发的初学者。我正在研究基于 BLE 的应用程序。今天我更新了 Xcode 8、iOS 10 并将我的代码转换为 swift3。然后我的一些语法需要转换。修复此问题后,我在 CBCharacteristic 上发现了一个问题。

问题

在 didUpdateValueforCharacteristic 中,我可以获得更新的 CBCharacteristic 对象。如果我打印出整个对象,它会正确显示。 -> 值 = <3a02>当我从 CBCharacteristic 检索值时,characteristic.value -> 2bytes(此值的大小)

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic:     CBCharacteristic, error: Error?)
{
if (characteristic.uuid.description == LED_WAVELENGTH_CHARACTERISTIC_UUID)
{
print("Characteristic - \(characteristic)")
print("Data for characteristic Wavelength - \ (characteristic.value)")
}
}

Log Result :

Characteristic - <CBCharacteristic: 0x1742a50a0, UUID = 2C14, properties = 0xE, value = <3a02>, notifying = NO>
Data for characteristic Wavelength - Optional(2 bytes)

PS:此代码在以前的版本上完全可以正常工作。

感谢关注,希望有人能帮我解决这个问题。

最佳答案

看来你一直依赖descriptionNSData返回 <xxxx> 形式的字符串为了检索您的数据的值(value)。正如您所发现的,这是脆弱的,因为 description函数仅用于调试,可以在没有警告的情况下更改。

正确的方法是访问包装在 Data 中的字节数组目的。这变得有点棘手,因为 Swift 2 允许您将 UInt8 值复制到单个元素 UInt16 数组中。 Swift 3 不允许您这样做,因此您需要自己计算。

var wavelength: UInt16?
if let data = characteristic.value {
var bytes = Array(repeating: 0 as UInt8, count:someData.count/MemoryLayout<UInt8>.size)

data.copyBytes(to: &bytes, count:data.count)
let data16 = bytes.map { UInt16($0) }
wavelength = 256 * data16[1] + data16[0]
}

print(wavelength)

关于ios - swift3中的CB特征值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com