BLE is a technology for low-power wireless communication. It is built for the low consumption of electricity. In particular, it targets health, fitness, beacons, etc. Back in 2011, Apple launched BLE on iPhone 4s, and today most of the iOS and Android devices are compatible with BLE. You have to use the CoreBluetooth Platform to integrate BLE with your app.
What is this about?
Let’s Understand what is CBPeripheral
The CBPeripheral class represents remote peripheral devices that your app discovers with a central manager (an instance of CBCentralManager ).You use this class to discover, explore, and interact with the services available on a remote peripheral that supports Bluetooth low energy.
Let’s Understand what is CBCentralManager
CBCentralManager objects manage discovered or connected remote peripheral devices (represented by CBPeripheral objects), including scanning for, discovering, and connecting to advertising peripherals.
Let’s dive programmatically
To start BLE with importing CoreBluetooth
Now, We will use CBCentralManager and CBPeripheral classes, however we need to add delegate methods CBCentralManager and CBPeripheral protocols
As soon as we add CBCentralManager and CBPeripheral we have to add delegate for CBCentralManagermethod
Now we will add UIButton in Controller and create Action to ViewController. To start with searching we have to declare variables of CBCentralManager and CBPeripheral. Now we will initialize the CBCentralManager variable in our Search Button Action.
This will help us to get different states of CBCentralManager. To prevent app from crashing we need to add permission to our App. Simply open info.plist and add Privacy – Bluetooth Always Usage Description, Privacy – Bluetooth Peripheral Usage Description. Do not forget to add a message in the value field.
Now build and run the app, and click on the Start Search button. You can see the App is asking for permission. Press OK when permission is prompted to use Bluetooth.
Now, we will add a different state of CBCentralManager in the centralManagerDidUpdateStatemethod
If you will build and run the app followed by clicking on the button you can see central.state is .powerdOn in your debug area. Now we want to scan for nearby bluetooth devices. For that we have to add a line.
It's preferable to add the line when the central state is powered On.
Now we want to see devices which are available, for that we need to add CBCentralManagerDelegate method centralManager(_:didDiscover:advertisementData:rssi:)
Now, we’re just left to connect to a particular Peripheral, so for that we will connect the Peripheral just after it is discovered by CentralManager. When we will connect to peripheral we will also stop centralManager to scan further as we have found Peripheral
There are still substantially more scopes to discover in BLE. Stay tuned with us for the next step of BLE.