swift3中的CBC特征值 [英] CBCharacteristic value in swift3

查看:195
本文介绍了swift3中的CBC特征值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am beginner in swift development. I was working on BLE based application. Today I updated Xcode 8, iOS 10 and convert my code to swift3. Then some of my syntax are need to convert. After fixing this , I found one issue on CBCharacteristic.

问题

Issue

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

Inside didUpdateValueforCharacteristic , I can get updated CBCharacteristic object. If I print out whole object, it show correctly. -> value = <3a02> When I retrieved value from CBCharacteristic , characteristic.value -> 2bytes (size of this value)

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:此代码完全正常工作以前的版本很好。

PS : This code is completely working fine on previous version.

感谢关注并希望有人可以帮我解决这个问题。

Thanks for attention and hope someone can help me to fix this issue.

推荐答案

看来你一直在依赖 NSData 描述返回一个字符串< xxxx> 形式,以便检索数据的值。正如您所发现的那样,这很脆弱,因为 description 函数仅用于调试,并且可以在没有警告的情况下进行更改。

It seems that you have been relying on the description of NSData returning a string of the form <xxxx> in order to retrieve the value of your data. This is fragile, as you have found, since the description function is only meant for debugging and can change without warning.

正确的方法是访问包含在 Data 对象中的字节数组。这已经变得有点棘手了,因为Swift 2会让你将UInt8值复制到单个元素UInt16数组中。 Swift 3不允许你这样做,所以你需要自己做数学。

The correct approach is to access the byte array that is wrapped in the Data object. This has been made a little bit more tricky, since Swift 2 would let you copy UInt8 values into a single element UInt16 array. Swift 3 won't let you do this, so you need to do the math yourself.

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) 

这篇关于swift3中的CBC特征值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆