C ++中swift3的特性值

我是快速发展的初学者。 我正在研究基于BLE的应用程序。 今天我更新了Xcode 8,iOS 10并将我的代码转换为swift3。 然后我的一些语法都需要转换。 解决这个问题之后,我发现了一个关于CBC特性的问题。

问题

在didUpdateValueforCharacteristic里面,我可以得到更新的CBCharacteristic对象。 如果我打印出整个对象,则显示正确。 – > value = <3a02>当我从CBCharacteristic中检索到值时,特征值 – > 2字节(这个值的大小)

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)") } } 

日志结果:

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

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

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

看来你一直依靠NSDatadescription来返回一个<xxxx>forms的string,以便检索你的数据的值。 正如你所发现的那样,这是脆弱的,因为description函数只是用于debugging,可以在没有警告的情况下改变。

正确的方法是访问包装在Data对象中的字节数组。 这已经有点棘手了,因为Swift 2会让你将UInt8的值复制到一个单一的UInt16数组中。 斯威夫特3不会让你这样做,所以你需要自己做math。

 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) 

现在,您可以使用String(bytes: characteristic.value!, encoding: String.Encoding.utf8)来获取特征的string值。