Table of Contents

Introduction

Building an iOS app that supports wearables and hearables using Bluetooth and BLE (Bluetooth Low Energy) opens up a world of possibilities for creating seamless and integrated user experiences. Whether you’re looking to connect smartwatches, fitness trackers, or wireless earbuds, understanding the core components of Bluetooth communication on iOS is crucial. Here’s a step-by-step guide to help you get started. 

Understanding the Basics of Bluetooth and BLE  

Before diving into code, it’s important to understand the difference between Bluetooth Classic and BLE: 

  • Bluetooth Classic is suitable for applications that require continuous streaming of data, such as audio. 
  • Bluetooth Low Energy (BLE) is designed for applications where power consumption is critical, such as fitness trackers or heart rate monitors. BLE is ideal for periodic data exchange.

Setting Up Your Xcode Project

Start by creating a new iOS project in Xcode. Choose a template that fits your app’s needs, such as a Single View App or a more complex template depending on your app’s architecture. 

Ensure that your project’s deployment target supports the devices you’re aiming to connect with. You might need to include the CoreBluetooth framework, which is essential for BLE communication. 

  1. Go to your project’s settings. 
  2. Under General, scroll down to Frameworks, Libraries, and Embedded Content. 
  3. Click the + button, search for CoreBluetooth, and add it to your project. 
  4. Enabling Background Modes for Bluetooth 

If your app needs to communicate with wearables or hearables while running in the background, you’ll need to enable the appropriate background modes: 

  • Go to the Signing & Capabilities tab in your project settings. 
  • Click the + Capability button and select Background Modes. 
  • Check “Uses Bluetooth LE accessories” and “Acts as a Bluetooth LE accessory” if necessary. 

Implementing CoreBluetooth in Your App 

Now that your project is set up, you can start implementing Bluetooth functionality using the CoreBluetooth framework. There are two primary roles your app might take: 

Central:

  • The central is the device that scans for, connects to, and communicates with peripherals. 
  • In an iOS app, the central role is represented by the CBCentralManager class. This class manages the discovery and connection to nearby peripheral devices. 
  • Once connected, the central can read from, write to, and subscribe to the characteristics of the peripheral. 
  • The central is the device that scans for, connects to, and communicates with peripherals. 
  • In an iOS app, the central role is represented by the CBCentralManager class. This class manages the discovery and connection to nearby peripheral devices. 
  • Once connected, the central can read from, write to, and subscribe to the characteristics of the peripheral.

Example Use Case: An iPhone acting as a central device might connect to a Bluetooth heart rate monitor (the peripheral) to read the heart rate data. 

Peripheral:

  • The peripheral is the device that advertises data and provides services and characteristics that the central can discover and interact with. 
  • In an iOS app, the peripheral role is represented by the CBPeripheralManager class. This class allows the iOS device to act as a peripheral, advertising services and characteristics to central devices. 
  • The peripheral typically has less processing power and might be a small device like a sensor or wearable that sends data to a more powerful central device. 
  • Example Use Case: Apple Watch: Communicates with an iPhone or other devices acts as a peripheral, advertising data that the iPhone (acting as a central) can discover and connect to. 

Example Use Case: Apple Watch: Communicates with an iPhone or other devices acts as a peripheral, advertising data that the iPhone (acting as a central) can discover and connect to. 

Here’s a simple example of how to set up your app as a central device: 

Swift code sample:- 

import CoreBluetooth 

class BluetoothManager: NSObject, CBCentralManagerDelegate { 

    var centralManager: CBCentralManager? 

    override init() { 

        super.init() 

        centralManager = CBCentralManager(delegate: self, queue: nil) 

    } 

    func centralManagerDidUpdateState(_ central: CBCentralManager) { 

        switch central.state { 

        case .poweredOn: 

            // Bluetooth is on, start scanning for devices 

            centralManager?.scanForPeripherals(withServices: nil, options: nil) 

        case .poweredOff: 

            // Bluetooth is off, handle accordingly 

        default: 

            break 

        } 

    } 

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) { 

        // Handle discovered peripherals 

        print(“Discovered \(peripheral.name ?? “Unknown Device”)”) 

    } 

} 

Connecting to and Communicating with Devices 

Once you’ve discovered a peripheral, you’ll need to connect to it and explore its services and characteristics. This is where you’ll handle the actual data exchange. 

swift sample code:- 

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { 

    peripheral.delegate = self 

    peripheral.discoverServices(nil) 

} 

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 

    if let services = peripheral.services { 

        for service in services { 

            peripheral.discoverCharacteristics(nil, for: service) 

        } 

    } 

} 

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 

    if let characteristics = service.characteristics { 

        for characteristic in characteristics { 

            // Read or write data as needed 

            if characteristic.properties.contains(.read) { 

                peripheral.readValue(for: characteristic) 

            } 

        } 

    } 

} 

Handling Bluetooth Permissions and Privacy 

Starting with iOS 13, apps must explicitly request permission to use Bluetooth. Ensure you’ve added the appropriate privacy description in your Info.plist: 

xml 

<key>NSBluetoothAlwaysUsageDescription</key> 

<string>We use Bluetooth to connect to your wearable devices.</string> 

This will prompt the user for permission the first time your app tries to access Bluetooth. 

Testing with Real Devices 

Testing is critical when working with Bluetooth, as the behaviour in simulators can differ from real devices. Make sure to test your app with the actual wearables or hearables you intend to support. 

Optimising for Battery Life 

Since many wearables and hearables rely on BLE for extended battery life, make sure your app is optimised to minimise energy consumption. Avoid frequent scanning and unnecessary data transfers. Use connection intervals wisely to balance performance with power efficiency. 

Handling Disconnections and Errors 

Bluetooth connections can be unstable, especially with small devices like wearables. Implement robust error handling and ensure your app gracefully recovers from disconnections.

swift sample code:- 

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { 

    // Handle disconnection, perhaps by attempting to reconnect 

    centralManager?.connect(peripheral, options: nil) 

} 

Staying Updated with Bluetooth Developments 

Bluetooth technology is continually evolving, with new profiles and capabilities being introduced. Stay up-to-date with the latest developments by regularly checking Apple’s CoreBluetooth documentation. 

Conclusion

Building an iOS app that supports wearables and hearables via Bluetooth and BLE is both challenging and rewarding. By understanding the basics, carefully implementing the CoreBluetooth framework, and optimising for real-world use, you can create a seamless experience that enhances the way users interact with their devices. Whether you’re developing a health monitoring app or a smart home accessory, mastering Bluetooth communication will set your app apart in the increasingly connected world.