首页 文章

从特征中获得“ Value ”

提问于
浏览
0

下列...

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

..outputs ...

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

我想要“值”部分“01” .

3 回答

  • 0

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

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

    我要感谢OOPer在Apple Developer论坛上的回答 .

    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

    swift:在更新值时从特征中获取值 .

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

相关问题