Reputation: 495
The following...
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { print(characteristic) }
..outputs...
<CBCharacteristic: 0x1700b8180, UUID = FFE1, properties = 0x10, value = <01>, notifying = YES>
I want the "value" part "01".
Upvotes: 0
Views: 5580
Reputation: 63
If you are asking to parse the data when Peripheral communicates.
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print("ERROR didUpdateValue \(error)")
return
}
//BLE_Characteristic_uuid > Your BLE Char UUID
if characteristic.uuid == CBUUID(string: BLE_Characteristic_uuid) {
guard let value = characteristic.value else { return }
let content = String(data: value, encoding:.utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""//.filter { !" \n\t\r".contains($0) } ?? ""
print("Value Received:-->",content )
if let i = content.utf8.firstIndex(where: { $0 >= 32 }) {
if let asciiPrefix = String(content.utf8[..<i]) {
print(asciiPrefix)
}
}else{
return
}
}
}
The ASCII value of 32 corresponds to the space character (' '). Therefore, the expression content.utf8.firstIndex(where: { $0 >= 32 }) returns the index of the first non-control character in the UTF-8 representation of the content String. However you can control it as per your requirements.
32 (in ASCII, these are printable characters like letters, digits, punctuation, etc.).
String(content.utf8[..<i]): This creates a new String using a substring of the content string from its start (0) up to the index i (excluding i). In other words, it extracts the portion of the string up to the first non-control ASCII character (whose ASCII value is greater than or equal to 32) and assigns it to asciiPrefix.
It will also neglect \u{01}
Upvotes: 0
Reputation: 2237
swift: Get value from characteristic while update value.
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let value = characteristic.value
print(value)
}
Upvotes: -1
Reputation: 495
I want to thank OOPer on the Apple Developer Forums for this answer.
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
}
}
Upvotes: 0
Reputation: 667
According to the documentation you can access it by calling:
characteristic.value
, this will be an object of type Data
.
Then you can transform this object to string.
Like this:
let data = characteristic.value
var dataString = String(data: data, encoding: String.Encoding.utf8)
Upvotes: 2