BLE & WIFI Communication in Android & iOS
Technostacks
Bluetooth and Wi-Fi are the most common tech approaches applied to provide wireless communication. In comparison with Wi-Fi, Bluetooth Low Energy (BLE) consumes less power and is battery-compatible as well.
BLE provides an accurate data transfer rate for most IoT-enabled mobile apps; it allows the application of IoT devices to operate efficiently for a period on a single charge.
Wi-Fi is an important enabler of the IoT devices and projects. Similarly, integration, as well as interoperability offered by Wi-Fi communication, facilitates IoT-based mobility solutions to interconnect safely one another and numerous user base devices to empower enhanced value from the IoT-based mobile applications and closely involved technology environments.
BLE & WIFI Communication in iOS
Overview of BLE for iOS Applications
Core Bluetooth is a fundamental framework usually integrated into iOS, macOS, watchOS, and tvOS when developing apps that interact with Bluetooth Low Energy (BLE).
As discussed above that BLE is the explicit wireless communication protocol designed in the special consideration of low-powered short-range communication between the devices so it would be ideally perfect to facilitate IoT-based devices and tech projects.
Technology Prerequisites
- Macbook, Mac Mini, iMac
- XCode
- iPhone with BLE (iPhone 4S onwards)
- BLE Peripheral (Hardware device)
Read more:- Mobile App Development Frameworks For App Developers
How Can You Work With Core Bluetooth in Swift?
The Core Bluetooth framework lets your application communicate with the Bluetooth low-energy devices. For example, discover, seek out, and connect to lower energy peripheral devices like explicit monitoring devices, digital thermostats, higher granularity smart metering information systems, and other types of iOS-based devices in multiple industries sector. We will even explore enablement of an app in Swift.
1. Setting Permissions:
- NSBluetoothAlwaysUsageDescription key if you are leveraging iOS13 or NSBluetoothPeripheralUsageDescription if leveraging iOS12 or previous.
- This is the message displayed to user while requesting Bluetooth Permission for the application.
2. Import CoreBluetooth:
Here is how we import Core Bluetooth function.
import CoreBluetooth
3. Delegate Setup and Initialize CBCentralManager:
- Create a class that conforms to the CBCentralManagerDelegate and optionally the CBPeripheralDelegate protocols. These delegates are responsible for handling and precisely dealing with central manager events.
- Create an instance of CBCentralManager to manage BLE central operations.
var centralManager: CBCentralManager! override func viewDidLoad() { super.viewDidLoad() centralManager = CBCentralManager(delegate: self, queue: nil) }
4. Implement Central Manager Delegate Methods:
Implement the delegate methods and tech approaches to respond to specific events, like discovering peripherals, connecting to them, and managing their services, features, and involved characteristics.
extension YourViewController: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn { // Bluetooth is ready, start scanning for peripherals centralManager.scanForPeripherals(withServices: nil, options: nil) } else { // Handle other states } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // A peripheral was discovered, you can connect to it here } }
5. Connecting to a Peripheral:
Once you have discovered a peripheral, you can initiate a connection and explore its functionalities, services and characteristics.
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // Connect to the discovered peripheral centralManager.connect(peripheral, options: nil) } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { // The connection to the peripheral was successful, you can now discover services and characteristics peripheral.delegate = self peripheral.discoverServices(nil) }
6. Peripheral Delegate Methods:
For devices acting as a peripheral, you will also need to enable and implement the CBPeripheralDelegate methods.
extension YourViewController: CBPeripheralDelegate { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { // Services were discovered, you can now explore their characteristics for service in peripheral.services ?? [] { peripheral.discoverCharacteristics(nil, for: service) } } // Handle characteristics discovery, read/write operations, notifications, etc. }
Read more:- Placing 3D Objects In Real-World With SwiftUI
Our team has extensive experience in working with various Swift applications for clients worldwide. If you need Swift development services, you can hire dedicated Swift developers from us. Our team of expert app developers will ensure that your project requirements are met with ease and efficiency.
Read more:- Predictions For the Future of IoT and Mobile App Integration
WIFI Communications in iOS
We have applied Wi-Fi functionalities and diverse range of technology approaches across projects that facilitates wireless communication.
Here are the technology Requirements for the same.
1. iOS11 SDK or later:
Make sure you are developing your app using Xcode and the iOS 11 SDK or a later version.
2. Add Hotspot Configuration Entitlement to your project:
In Xcode, go to your project settings, and under the “Signing & Capabilities” tab, add the “Hotspot Configuration” capability to your app.
3. Adding Permissions:
- Info.plist file, add the necessary permissions to access the local network.
- NSLocalNetworkUsageDescription: Describe why your app needs access to local networks.
- NSBonjourServices: An array of Bonjour service names your app will search for.
Read more:- Localization in SwiftUI – String Catalogs with Xcode 15
Implementation
Let us explore how to import, configure and enable connection functionalities in a Wi-Fi network.
1. Import NetworkExtension framework:
Import NetworkExtension
2. Configure and connect to the Wi-Fi network:
- Use the NEHotspotConfigurationManager and NEHotspotConfiguration classes to configure and connect to the desired Wi-Fi network.
- You will need the SSID and password of the target network.
let configuration = NEHotspotConfiguration(ssid: "NetworkSSID", passphrase: "NetworkPassword", isWEP: false) configuration.joinOnce = true // Connect once and forget NEHotspotConfigurationManager.shared.apply(configuration) { error in if let error = error { print("Error configuring Wi-Fi: \(error.localizedDescription)") } else { print("Wi-Fi configured successfully") } }
Your custom hardware should be correctly set up both as an access point of a Wi-Fi network, or it is on the same Wi-Fi local network as your iOS device. Make sure you have it in place of the IP address and port number of the hardware that you will be contacting through your project.
Successful Technology Projects Involving a Diverse Range of Chips
Earlier, have worked on successfully proven tech projects and applications involving chips exactly leveraged in multiple IoT and wireless communication:
- NRF52840
- NRF52832
- ESP32
- ESP8266
- Raspberry Pi
- RS9116 Wi-Fi NCP SoCs
- Silicon Lab’s RS9116 Wi-Fi NCP SoCs
- ST Microcontroller’s BlueNRG-LP
BLE & WIFI Communication in Android
What is BLE?
Bluetooth Low Energy(BLE) is a wireless communication technology that one uses for short-range communication with low power consumption. In Android, one interacts with BLE devices through the BluetoothGatt API. Below is the guide to setting BLE in Android using Kotlin.
Prerequisites
- Android Studio 3.0 or later versions.
- A physical Android device with BLE support(Android 4.3 or later).
- The BLE Device you want to communicate to.
How To Start With BLE in An Android Project Using Kotlin?
Step 1: Set up the permissions:
Add the following permissions to your AndroidManifest.xml file to access Bluetooth features:
.... ....
Step 2: Initialize BluetoothAdapter:
Before you can start using BLE, you need to obtain a reference to the BluetoothAdapter:
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager val bluetoothAdapter = bluetoothManager.adapter if (bluetoothAdapter == null) { //Device does not support Bluetooth return }
Step 3: Scan for BLE Devices
To discover nearby BLE devices, start a scan:
val scanner = bluetoothAdapter.bluetoothLeScanner val scanCallback: ScanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult?) { // Handle the scan result here } } val scanFilter = ScanFilter.Builder() .setServiceUuid(ParcelUuid(UUID.randomUUID())) .build() val filters = listOf(scanFilter) val scanSettings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) .build() scanner.startScan(filters, scanSettings, scanCallback) scanner.stopScan(scanCallback)
You can additionally add parameters like setDeviceName and setServiceUuid to scan for only devices with specific names and/or a specific UUID.
Always remember to stop scanning once you are done with the scanning.
scanner.stopscan(scancallback)
Step 4: Establish BLE Connection
Once you’ve found the device you want to connect to, establish a BLE connection:
val device = result?.device // Obtain the device from scan result val gattCallback: BluetoothGattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (newState == BluetoothProfile.STATE_CONNECTED) { // Connected to the device, discover services gatt.discoverServices() } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // Disconnected from the device } } } val gatt = device?.connectGatt(this@DemoClass, false, gattCallback)
Step 5: Discover Services and Characteristics
After the connection is established, you can discover services and characteristics:
val gattCallback: BluetoothGattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (newState == BluetoothProfile.STATE_CONNECTED) { // Connected to the device, discover services gatt.discoverServices() } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // Disconnected from the device } } override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { super.onServicesDiscovered(gatt, status) if (status == BluetoothGatt.GATT_SUCCESS) { // Check the discovered services for (service in gatt.services) { // Check the discovered characteristics for a service for (characteristic in service.characteristics) { // Handle characteristics } } } } }
Step 6: Read and Write Data
You can read and write data from/to BLE characteristics:
// Reading data gatt?.readCharacteristic(characteristic) // Writing data if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { gatt?.writeCharacteristic(characteristic, byteArrayOf(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) } else { characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT characteristic.value = byteArrayOf() gatt?.writeCharacteristic(characteristic) }
Step 7: Disconnect and Close
When you’re done with the connection, disconnect and close the GATT connection:
gatt?.disconnect() gatt?.close()
How To Start With WiFi In An Android Project Using Kotlin?
Step 1: Set up the permissions:
Add the following permissions to your AndroidManifest.xml file to access WiFi features:
.... ....
Step 2: Check whether WiFi is enabled:
Before you can start using WiFi, you need to enable WiFi if it is not turned on:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager if (!wifiManager.isWifiEnabled) { val panelIntent = Intent(ACTION_WIFI) activityResultLauncher.launch(panelIntent) } else { //WiFi enabled. Connect to WiFi here } } else { val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager // Check if Wi-Fi is enabled if (!wifiManager.isWifiEnabled) { wifiManager.isWifiEnabled = true } else { //WiFi enabled. Connect to WiFi here } }
Step 3: Connect with a WiFi device
Start connection with the WiFi device using the network SSID and network password.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { /** * Build the WifiNetworkSpecifier and add the desired network ssid and network password * to connect with */ val wifiSpecifier = WifiNetworkSpecifier.Builder() .setSsid(ssid) .setWpa2Passphrase(password) .build() /** * Build a NetworkRequest object to connect with the wifi by adding the WifiNetworkSpecifier * and the transport type to TRANSPORT_WIFI */ val networkBuilder = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .setNetworkSpecifier(wifiSpecifier) .build() //Use ConnectivityManager to create a request to connect with the specified Wifi network val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connectivityManager.requestNetwork(networkBuilder, NetworkCallback()) } else { // Create a WifiConfiguration for the network val wifiConfig = WifiConfiguration() wifiConfig.SSID = "\"$ssid\"" wifiConfig.preSharedKey = "\"$password]\"" // Add the network configuration and attempt to connect val networkId = wifiManager.addNetwork(wifiConfig) //Check the configured networks to find the network based on the SSID and connect to it wifiManager.configuredNetworks.find { it.SSID == "\"$ssid\"" } ?: run { // Disconnect from the current network wifiManager.disconnect() // Enable the newly configured network wifiManager.enableNetwork(networkId, true) // Reconnect to the new network wifiManager.reconnect() } }
This code will be connected to all the devices with WiFi mobile and stay connected until the whole of the application is closed. The WiFi itself will be disconnected when the application is closed.
Chips we have used in various IoT and wireless communication applications:
- NRF52840
- NRF52832
- ESP32
- ESP8266
- Raspberry Pi
- RS9116 Wi-Fi NCP SoCs
- Silicon Lab’s RS9116 Wi-Fi NCP SoCs
- ST Microcontroller’s BlueNRG-LP
We Have Successfully Developed BLE Applications for iOS & Android For Various Industries
We at Technostacks, a top mobile app development company have experience in creating BLE apps for both Android and iOS platforms. We have a dedicated team of app developers who can work with diverse technologies and meet your project requirements. You can contact us for your custom app development.
We have discussed a few of the industries and tech domains that we delivered and can facilitate with modern-day app features.
Healthcare and Fitness:
Connect them with fitness trackers, heart rate monitors, smart scales, blood pressure devices and other health and wellness related devices.
Monitor a user’s health data and provide valuable insights both for individual usage purposes as well as for medical monitoring purposes.
Smart Home and Home Automation:
We have built the solutions for controlling the smart home devices like smart locks, smart lights and many more automation applications.
Retail and Marketing:
Enable proximity marketing along with customer engagement through beacons. BLE technology allows retailers to send location-sensitive offers, coupons, product information by customers when they move through the physical store locations.
Industrial and Manufacturing:
Control and monitor industrial equipment and machinery. They enable remote monitoring, maintenance, and remote sensing of the installed sensors.
Logistics and Supply Chain:
Track assets, monitor inventory and locate shipments within warehouses and during transportations. We successfully increased the efficiency of logging operation providing real-time datasets about the location and status of the items in wide range of tech projects.
Agriculture and Farming:
Attach to agricultural sensors and devices for tracking soil moisture and temperature.
We have successfully implemented projects that tracked hand-harvested crops, and communicate usages with BLE Printers for receiving automated receipts.
Wearable Technology:
Smartwatches make use of this BLE technology in connecting and relating to the mobile smartphone and other devices. They can offer efficient notification reporting, activity tracking with its progress monitoring, as well as task tracking among other automation functionalities.
Indoor navigation:
Bluetooth beacons have been employed towards the development of projects allowing for accurate indoor location and tracking majorly indoors.
Environmental Monitoring:
For air quality, water level, smoke-detection, environment-related parameters we have deployed BLE enabled sensors in various projects.
Moving Forward
The substantial intent and objective of this blog post is to showcase on BLE & WIFI communication across IoT projects and also on how we can work with core Bluetooth in swift.
Explore our project case studies here:-
https://technostacks.com/our-work/
We at Technostacks can work with any kind of custom app development along with advanced technology projects. Our teams have proven expertise in working with this kind of IoT applications involving BLE & WIFI communication for Android and iOS platforms.