2016-09-27 152 views
0

下获取的 “价值” ......从特征

 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { 
     print(characteristic) 
    }

..outputs ...

<CBCharacteristic: 0x1700b8180, UUID = FFE1, properties = 0x10, value = <01>, notifying = YES>

我想要的 “值” 部分 “01”。

+0

'characteristic.value'会给一个NSData对象''<01>,但它是由你来是十六进制转换成你想要的值(字符串编码?int值?等等)。 – Larme

回答

1

根据documentation,您可以通过拨打电话: characteristic.value访问它,这将是Data类型的对象。 然后您可以将此对象转换为字符串。 像这样:

let data = characteristic.value 
var dataString = String(data: data, encoding: String.Encoding.utf8) 
+0

输出可选(“\ u {01}”)。我怎样才能得到01? – Chris

+0

我想做一个条件:if dataString ==“01 {// do stuff} – Chris

0

我要感谢OOPer在苹果开发者论坛对这个答案。

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { 
    guard let data = characteristic.value else { 
     return 
    } 
    if data.elementsEqual([0x01]) { //<- You can directly compare a Data to an Array of bytes. 
     //do something 
    } 
} 
-1

迅速:从特征而更新值 获得价值。

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { 

     let value = characteristic.value 

     print(value) 
} 
+0

尽管这段代码可能是解决方案,[包括解释](// meta.stackexchange.com/questions/114762/解释完全基于代码的答案)真的有助于提高你的帖子的质量。请记住,你正在回答未来读者的问题,而这些人可能不知道你的代码建议的原因。 – yivi