我有可与 BLE 设备配合使用的应用程序。我有特征值,但无法将其转换为字符串。 例如,
value = <aa640400 0000001e 0f>
如何将其转换为字符串?
let dd = getCharacteristic.value!;
print(String(data: dd, encoding: String.Encoding.ascii)!);
我使用了上面桑迪的答案并将其浓缩为
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}
我不需要。
请按照以下代码操作:
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)