Dec 21, 2016

How to Get a Response from a CoreBluetooth Write

You write to a Bluetooth device in CoreBluetooth using the CBPeripheral method writeValue(_:for:type:). You can ask the peripheral for confirmation by indicating the type, which is either .withResponse or .withoutResponse. If you pass .withResponse, how do you get that response?

You will be notified in a delegate callback peripheral(_:didWriteValueFor:error:) This method is passed a CBPeripheral, a CBCharacteristic, and an Error?. The response indicates one of two things:

  1. An error occured, indicated by an Error passed in the error parameter.
  2. The write was successful, indicated by a nil error.

That's it. Don't expect any aditional messages as part of the response. The delegate is passed a CBCharacteristic, which has a value field. Maybe that contains more info? Actually, no. That contains the last read value of the characteristic. It won't indicate the just written new value, even if the delegate receives confirmation that the write was a success.

If you want the new value of the characteristic, you can read it with readValue(for:). If you have subscribed to notifications with setNotifyValue(_:for:), you will automatically get a callback when the value changes. Either way, you wont't get an automatic notification of the new value as part of the write confirmation response.