【问题标题】:Convert CBCharacteristic value to string将 CBCharacteristic 值转换为字符串
【发布时间】:2017-01-24 18:09:55
【问题描述】:

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

value = <aa640400 0000001e 0f>

如何转成字符串?

【问题讨论】:

    标签: ios objective-c core-bluetooth


    【解决方案1】:
    let dd = getCharacteristic.value!;
    
    print(String(data: dd, encoding: String.Encoding.ascii)!);
    

    【讨论】:

    • 请在您的代码中添加说明。代码转储经常被否决,甚至可能被删除。
    • 让值 = [UInt8](characteristic.value!)
    【解决方案2】:

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

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

    我想要做的就是从 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}
    

    我不需要。

    【讨论】:

    【解决方案3】:

    按照以下代码:

    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)
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多