swift3中的CBC特征值

Nyo*_*Lay 3 ios bluetooth-lowenergy cbperipheral swift3 xcode8

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

问题

在didUpdateValueforCharacteristic中,我可以获得更新的CBC特性对象.如果我打印出整个对象,它会正确显示. - > value = <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)")
        }
 }
Run Code Online (Sandbox Code Playgroud)

记录结果:

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

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

感谢您的关注,希望有人可以帮我解决这个问题.

Pau*_*w11 5

看来你已经依靠descriptionNSData返还形式的字符串<xxxx>,以检索您的数据的价值.正如您所发现的那样,这很脆弱,因为该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) 
Run Code Online (Sandbox Code Playgroud)