2016-09-27 166 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