2017-02-13 150 views
2

我目前正在使用CoreBluetooth工作在BLE設備上。我可以通過CBCentralManagerDelegate找到我的設備,並與我的設備連接。如何讀取特徵值?

當我想發現一個服務的特徵時,我可以得到正確的uuid,但是特徵值是nil。有任何想法嗎?

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 
    if error != nil { 
     print("ERROR DISCOVERING CHARACTERISTICS: \(error?.localizedDescription)") 
     return 
    } 
    if let characteristics = service.characteristics { 

     for characteristic in characteristics { 
      print("--------------------------------------------") 
      print("Characteristic UUID: \(characteristic.uuid)") 
      print("Characteristic isNotifying: \(characteristic.isNotifying)") 
      print("Characteristic properties: \(characteristic.properties)") 
      print("Characteristic descriptors: \(characteristic.descriptors)") 
      print("Characteristic value: \(characteristic.value)") 
     } 
    } 
} 

------------------------------------------------------------------- 
Characteristic UUID: FA01 
Characteristic isNotifying: false 
Characteristic properties: CBCharacteristicProperties(rawValue: 26) 
Characteristic descriptors: nil 
Characteristic value: nil 

有關屬性的另一個問題,根據Bluetooth SIG

enter image description here

爲什麼nRFConnect顯示了readwritenotify。但它確實獲得了該特徵的正確價值。

enter image description here

+2

直到發出讀取請求並獲得對'didUpdateValue' CBPeripheralDelegate方法的回調之前,該值爲零。 – Paulw11

+0

當你發現它時,調用'func readValue(用於特徵:CBCharacteristic)'。或setNotify(如果可用於字符)。 – Larme

+0

它的工作原理。這些物業怎麼樣? – WeiJay

回答

0

讀取特徵值。 swift 4

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 
    for newChar: CBCharacteristic in service.characteristics!{ 

      peripheral.readValue(for: newChar) 
     }