【发布时间】:2017-07-24 10:18:48
【问题描述】:
我在 Swift 中使用 CoreBluetooth 库,我想阅读我从 Characteristic 中的外围设备接收到的内容。当我将特征的值转换为 NSString 时,它总是返回 nil。你知道为什么吗 ?我认为是因为编码,因为我有一个可以读写的特性,当我向它写东西时,我可以阅读我写的东西。当我写的时候,如果我写 6,那么 Characteristic 的值为 36,并且这段代码有效。如果我只想读取一个特征,则代码不起作用。
这就是我的特征所包含的
<CBCharacteristic: 0x1700a2a60, UUID = FFF2, properties = 0x2, value = <02>, notifying = NO>
这是代码
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if error != nil {
print("Error on updating value on characteristic: \(characteristic) - \(String(describing: error?.localizedDescription))")
return
}
print(characteristic.value!)
print(NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)!). //HERE IS NULL
guard let stringFromData = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) else
{
print("Invalid data")
return
}
//ALSO HERE stringFromData IS NULL
}
【问题讨论】:
-
这里是 print(characteristic.value!) ?
-
它显示 1 个字节
-
您可以尝试 ascii 编码,但如果您的数据是通过外围设备的“虚拟串行端口”发送的,您可能需要收集多个数据包来获取您的字符串
-
这应该是什么价值?可以改为 Int 吗?
标签: ios swift core-bluetooth