Bluetooth Low Energy on iOS: The Easy Way
I don’t know about you, but the first time I had to do something related
with BLE and iOS I was about to kill myself … Ok, not really but I can assure you that I didn’t like the API at all. The responsibility might be shared between Apple and BLE’s designers. The thing is that the API requires a lot of boilerplate and delegates just to read a byte from the BLE device.
Every operation is asynchronous and the CoreBluetooth translates into a lot of code just to establish a connection or perform a read. In addition, it delegates what you have to implement: CBCentralManagerDelegate andCBPeripheralDelegate. It has so many responsibilities (or at least that is what I think), that it’s pretty simple to end up with a lot of spaghetti code. For example, CBCentralManagerDelegate has methods both for the discovery process and the connection process. Those groups of methods could be separated.
My first bits of code with CoreBluetooth was for Syrmo, a tracking device for skateboards that connects with your phone and shows you stats for every trick you do with your skateboard. My first attempt did the job, but the code was really ugly. After a couple of changes and a better understanding of the framework I came to a solution that I liked. Then I started to work on other BLE related projects and common patterns started to emerge. This was the moment in which I decided to extract the code into a library.
I wanted to make a library that is easy to use and minimizes the boilerplate. That library is WLXBluetoothDevice, a block-based wrapper for CoreBluetooth that was designed with the following goals in mind:
-Avoid having to deal with complex asynchronous logic spread all over several delegate methods.
-Reduce the amount of ceremony necessary to start exchanging data between two devices.
-Handle all the `CBCentralManagerDelegate` and `CBPeripheralDelegate` methods internally and expose a block-based API to the user.
-Implement common use cases and patterns that are found in most BLE apps.
-Provide a clean architecture to build maintainable code upon it.
- Facilitate automated testing for Bluetooth dependent code.
Here are some of the most relevant features that are included in WLXBluetoothDevice:
-Connection timeouts
-Reconnection strategies
-Block-based API
-Automatic characteristic discovery
-NSNotifications for Bluetooth connection and discovery events.
-Storage service to remember devices.
You can check the documentation for a better explanation of how the library is designed and some examples. The library is battle-tested but if you find a bug or you have some feedback just create an issue.
Hope you like it! :-)
Posted by Guido Marucci Blas(guidomb@wolox.com.ar)