Updated for Swift3
After executing this method, the delegate your peripheral device will asynchronously receive the peripheral(_:didUpdateValueFor:error:) method. In this method, you can request the value passed parameter characteristic . value will be NSData from which you can infer bytes from. For instance.
// MARK: - CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let e = error { print("ERROR didUpdateValue \(e)") return } guard let data = characteristic.value else { return } ... }
The value method actually returns Optional around the expected Data , so let the guard path be the path.
Typically, a characteristic will have a simple value encoded in it up to a 20-byte Data payload. For instance. perhaps this is a simple UInt16 counter. For
To convert between these Data glumps and significant numbers, look at the Swift round lines to / from Data (I have included my implementation of this below).
So, for example, if you know that a characteristic of interest is some counter that should be retrieved as UInt16 , I would fill the above example with something like:
// MARK: - CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let e = error { print("ERROR didUpdateValue \(e)") return } guard let data = characteristic.value else { return } print("counter is \(UInt16(data:data))") } // Data Extensions: protocol DataConvertible { init(data:Data) var data:Data { get } } extension DataConvertible { init(data:Data) { guard data.count == MemoryLayout<Self>.size else { fatalError("data size (\(data.count)) != type size (\(MemoryLayout<Self>.size))") } self = data.withUnsafeBytes { $0.pointee } } var data:Data { var value = self return Data(buffer: UnsafeBufferPointer(start: &value, count: 1)) } } extension UInt8:DataConvertible {} extension UInt16:DataConvertible {} extension UInt32:DataConvertible {} extension Int32:DataConvertible {} extension Int64:DataConvertible {} extension Double:DataConvertible {} extension Float:DataConvertible {}
source share