Untitled Kingdom Blog - articles about MedTech innovation

Swift Playground: Bluetooth Low Energy

Written by Grzegorz Przybyła | Feb 7, 2020 10:55:00 AM

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;

  • 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 a 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:

 

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.