Have you ever wondered what it is like to work with Bluetooth Low Energy? Or maybe you think that BLE is a pain in the ass when you need to play with it on the iOS / MacOS side?
In this article, I would like to show that it is quite easy to start playing with it. And what is more, I did that in the MacOS Playground.
You can wonder why I am using the MacOS Playground while there already is so much content on how to work with iOS Playgrounds?
The answer is easy: using the iOS Playground means no access to the CoreBluetooth. (The truth is that there is access, but you'll get the << unsupported
>> error). Moreover, CoreBluetooth support is entirely necessary to work with BLE.
So let’s start:
We need to capture the onScannerReady
closure; as it can take some time while the hardware Bluetooth module starts, and only then, can we perform some action on the CBCentralManager (e.g. start scanning).
BluetoothScanner
is an NSObject
subclass because it is a CBCentralManagerDelegate requirement.
To find more information check:
https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerdelegate
Now we need to implement the protocol methods:
CBCentralManager
is ready we perform scannerReady closure; also, there is a good practice to remove the closure reference. Thanks to that, there is no way to use it again accidentally.
How hard can it be…?
Defining a separate method to start scanning can be handy as the CBCentralManagerDelegate is a lovely old-fashioned Obj-C API.
We need to save the onDiscover
closure, and perform it whenever CBCentralManager
returns new discovered CBPeripheral
And the implementation of the delegate method:
Let’s decompose this method into the first one;
It is handy to cover discovered peripheral by own protocol; It will be easier to display simple information about the peripheral.
So let us check is if it is working:
Works like a charm 🍀
Thank you for reading!
You can find a working playground example on my Github repo: https://github.com/gregiOS/Playgrounds
And to learn about the software development process in the Untitled Kingdom, check out this page.