将 CBCharacteristic 值转换为字符串

问题描述 投票:0回答:3

我有可与 BLE 设备配合使用的应用程序。我有特征值,但无法将其转换为字符串。 例如,

value = <aa640400 0000001e 0f>

如何将其转换为字符串?

ios objective-c core-bluetooth
3个回答
1
投票
let dd = getCharacteristic.value!;

print(String(data: dd, encoding: String.Encoding.ascii)!);

0
投票

我使用了上面桑迪的答案并将其浓缩为

let data = (characteristic.value)!    
let nsdataStr = NSData.init(data: (characteristic.value)!)
print("Raw: \(nsdataStr)")

我想做的就是从 BLE 外设(本例中为 HR 监视器)获取原始值(十六进制)。 上面的输出给了我:

// This is the Decimal HRArray:[22, 64, 90, 3] 
Raw: {length = 4, bytes = 0x16404e03}

下面的代码基本上只是删除了空格

let str = nsdataStr.description.trimmingCharacters(in:charSet).replacingOccurrences(of: " ", with: "")

制作它

Raw: {length=4, bytes=0x16404e03}

我不需要。


-1
投票

请按照以下代码操作:

let data = (characteristic?.value)!

print(data) //-> It will be of type Data we need to convert Data to String

let charSet = CharacterSet(charactersIn: "<>")

let nsdataStr = NSData.init(data: (characteristic?.value)!)

let str = nsdataStr.description.trimmingCharacters(in:charSet).replacingOccurrences(of: " ", with: "")

print(str) // you will get String or Hex value (if its Hex need one more conversion)
© www.soinside.com 2019 - 2024. All rights reserved.