Swift Playground: Bluetooth Low Energy
Have you ever wonder how it is 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 is so much content provided how to work with iOS Playgrounds? The answer is easy: using the iOS Playground we do not have access to the CoreBluetooth. (The truth is that we do have access, but we 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 hardware Bluetooth module starts, and only then we can 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:
As we can see, when 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;
rssi: NSNumber
which is the received signal strength indicator in a moment when central discovered peripheral.advertisementData
is a dictionary containing any advertisement data; e.g. advertised name or information is the device connectable. https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerdelegate/advertisement_data_retrieval_keys ←here you can find future information about that. 🚀CBPeripheral
is a CoreBluetooth object reference to given peripheral.CBCentralManager
good known reference to the object which calls this method
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:
Work like a charm 🍀
Thank you! You can find working playground example on my Github repo: https://github.com/gregiOS/Playgrounds
Read more from Unititled Kingdom: