- 16th Jul, 2021
- Hardik D.
26th Mar, 2021 | Jay R.
Bluetooth Low Energy (BLE) has become an integral part of modern mobile applications, enabling efficient communication between devices while consuming minimal power.
In the iOS ecosystem, Bluetooth Low Energy is widely used for a variety of applications, including health and fitness tracking, home automation, and location-based services.
This comprehensive guide aims to provide iOS developers with a solid understanding of Bluetooth Low Energy technology and how to leverage it in their applications.
Bluetooth Low Energy, often referred to as Bluetooth LE or BLE, is a wireless communication protocol designed for short-range communication with low power consumption.
It's especially suitable for devices like sensors, wearables, and other battery-powered devices that require intermittent communication. BLE operates in two roles: the central and peripheral.
The central device scans for nearby peripherals and initiates connections, while peripherals wait for connections and respond to requests.
This asymmetric communication model allows for efficient power usage in scenarios where one device (central) communicates with several others (peripherals).
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.
In iOS, Apple provides the Core Bluetooth framework for interacting with Bluetooth Low Energy devices. This framework allows developers to discover, connect to, and communicate with BLE peripherals.
Here's a brief overview of key concepts within Core Bluetooth:
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.
CBCentralManager objects manage discovered or connected remote peripheral devices (represented by CBPeripheral objects), including scanning for, discovering, and connecting to advertising peripherals.
To start BLE with importing CoreBluetooth
import UIKit
import CoreBluetooth
Now, we will use CBCentralManager and CBPeripheral classes, however we need to add delegate methods CBCentralManager and CBPeripheral protocols
class ViewController: UIViewController, CBPeripheralDelegate {
As soon as we add CBCentralManager and CBPeripheral we have to add delegate for CBCentralManagermethod
class ViewController: UIViewController, CBPeripheralDelegate {
private var centralManager: CBCentralManager!
private var peripheral: CBPeripheral!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
}
}
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.
@IBAction func actionStartSearching(_ sender: Any) {
centralManager = CBCentralManager(delegate: self, queue: nil)
}
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
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("central.state is .unknown")
case .resetting:
print("central.state is .resetting")
case .unsupported:
print("central.state is .unsupported")
case .unauthorized:
print("central.state is .unauthorized")
case .poweredOff:
print("central.state is .poweredOff")
case .poweredOn:
print("central.state is .poweredOn")
@unknown default:
print("central.state is Not Found")
}
}
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.
centralManager.scanForPeripherals(withServices: nil)
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:)
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if (peripheral.name == nil){
return
}
let DeviceName : String = peripheral.name!
print(DeviceName)
}
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
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if (peripheral.name == nil){
return
}
let DeviceName : String = peripheral.name!
print(DeviceName)
if DeviceName == "Sleep4U-" {
self.centralManager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
self.centralManager.connect(peripheral, options: nil)
}
centralManager.stopScan()
}
Bluetooth Low Energy is a powerful technology that has transformed the landscape of wireless communication, particularly in the realm of mobile applications.
For iOS developers, the Core Bluetooth framework provides the tools necessary to harness the capabilities of BLE seamlessly.
There are still substantially more scopes to discover in Bluetooth Low Energy.
Stay tuned with us for the next step of Bluetooth Low Energy.
References:
Get insights on the latest trends in technology and industry, delivered straight to your inbox.