Alex MitrovicBLE & IoT app developer, Android and iOS

iOS & KMP

CoreBluetooth state restoration: keeping an iOS BLE app connected in the background

How an iOS BLE app keeps working in the background: the bluetooth-central mode, pending connections and state restoration, with Swift code.

Short answer

To keep an iOS BLE app working in the background, enable the bluetooth-central background mode, create the CBCentralManager with a restore identifier, implement centralManager(_:willRestoreState:) to take back the restored peripherals, and use pending connect() calls, which never time out, to reconnect. iOS then relaunches the app in the background for Bluetooth events even after it was terminated for memory, but not after the user force-quits it.

Key takeaways

  • bluetooth-central background mode lets your app receive BLE events while in the background.
  • connect() on iOS never times out: a pending connect is the background reconnect mechanism.
  • State restoration needs a restore identifier at init and willRestoreState handled before anything else.
  • Background scans need service UUID filters, and duplicates are coalesced.
  • A user force-quit disables relaunch until they open the app again; that's by design.

On iOS, background BLE works differently from Android, and in some ways better: there's no foreground service, but the system can wake or even relaunch your app for Bluetooth events. Getting it right is mostly about three things: the background mode, pending connections and state restoration.

Step 1: the bluetooth-central background mode

Add bluetooth-central to UIBackgroundModes (in Xcode: Signing & Capabilities → Background Modes → “Uses Bluetooth LE accessories”). With it, iOS delivers delegate callbacks to your app in the background: notifications from the device, connection events, scan results. Without it, the app is suspended and events queue up until it comes back to the foreground.

Add NSBluetoothAlwaysUsageDescription to Info.plist too, with a sentence that says why the app uses Bluetooth. Without it the app crashes on first use.

Step 2: pending connections are your reconnect

centralManager.connect(peripheral) doesn't time out. If the device is out of range, the request stays pending until it comes back, and then iOS connects it, even with your app in the background. So the background reconnect strategy on iOS is simple: when didDisconnectPeripheral fires and the user still wants the device, call connect again immediately.

Background reconnect on iOS
func centralManager(_ central: CBCentralManager,
                    didDisconnectPeripheral peripheral: CBPeripheral,
                    error: Error?) {
    log("disconnect \(peripheral.identifier) error=\(String(describing: error))")
    guard wantsConnection(peripheral) else { return }
    central.connect(peripheral, options: nil) // pending until the device is back, no timeout
}

Step 3: state restoration

iOS can terminate a backgrounded app to free memory. With state restoration, it keeps the app's Bluetooth state (pending connections, connected peripherals, scans) and relaunches the app in the background when something happens, handing that state back.

Restoring state after a background relaunch
final class BleCentral: NSObject, CBCentralManagerDelegate {
    private var central: CBCentralManager!
    private var peripherals: [UUID: CBPeripheral] = [:]

    override init() {
        super.init()
        central = CBCentralManager(delegate: self, queue: bleQueue, options: [
            CBCentralManagerOptionRestoreIdentifierKey: "com.example.app.central" // stable, unique
        ])
    }

    // Called before centralManagerDidUpdateState when iOS relaunches the app.
    func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) {
        let restored = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] ?? []
        for p in restored {
            p.delegate = self               // take them back, or events go nowhere
            peripherals[p.identifier] = p
        }
    }

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        guard central.state == .poweredOn else { return }
        for p in peripherals.values {
            switch p.state {
            case .connected: p.services == nil ? p.discoverServices([myService]) : resubscribe(p)
            case .connecting: break         // still pending, nothing to do
            default: central.connect(p)     // pending connect again
            }
        }
    }
}

Two details that matter. Create the manager with the same restore identifier early in launch: on a background relaunch, application(_:didFinishLaunchingWithOptions:) receives launchOptions[.bluetoothCentrals] with the identifiers to restore. With the SwiftUI app lifecycle, use a UIApplicationDelegateAdaptor so this still runs. And do the minimum on relaunch: you have limited background time, so handle the event, save what you need and let the app be suspended again.

Scanning in the background

Background scanning works, with limits: you must pass service UUIDs to scanForPeripherals(withServices:) (nil finds nothing in the background), CBCentralManagerScanOptionAllowDuplicatesKey is ignored so each device is reported once, and scans run less often. If the device advertises its service UUID, and especially if the app already knows the peripheral, a pending connect is far more reliable than a background scan.

What iOS won't do

  • Relaunch after a force-quit. If the user swipes the app away, iOS treats it as “don't run this” and won't relaunch it for Bluetooth until the user opens it again.
  • Give you the MAC address. Peripherals have a UUID that's stable for your app on that phone. Put your own device ID in the advertising data.
  • Let you choose connection parameters. The device requests them within Apple's guidelines.
  • Run indefinitely. Each background wake comes with limited time. Long work belongs in the foreground or in short chunks.

Testing restoration

Restoration only happens after a system termination, which is hard to trigger on purpose. A common approach: add a debug-only action that calls kill(getpid(), SIGKILL) after the app has set up its connections, then make the device send a notification or come back into range, and watch the app relaunch in the background with logs. Don't test by swiping the app away; that's the one case restoration is designed not to cover.

Add what you learned from a real iOS project here: which part of restoration surprised you, or what the logs showed.

How this fits next to the Android side: background BLE on Android and Android vs iOS BLE.

FAQ

Can an iOS app stay connected to a BLE device in the background?

Yes, with the bluetooth-central background mode. The app receives Bluetooth events in the background; if iOS terminates it for memory, state restoration relaunches it in the background when a Bluetooth event concerns it.

Why doesn't my iOS app relaunch for Bluetooth events?

The most common reason is that it was force-quit by the user, which disables relaunch until the app is opened again. Otherwise check the restore identifier, that the manager is created early at launch, and that willRestoreState re-assigns peripheral delegates.

Does CBCentralManager.connect time out?

No. A connect request stays pending until the peripheral is available or you call cancelPeripheralConnection. That makes it the natural way to reconnect in the background; add your own timeout only for connections the user is actively waiting for.

Can iOS scan for BLE devices in the background?

Yes, but only with specific service UUIDs, with duplicate reports coalesced and at a lower rate. For known devices, a pending connect is more reliable than a background scan.

Sources

Seeing this in your own app?

Send me the phone models and what the logs say. On a short call I'll tell you where I'd look first.

Book a free call

Free · NDA on request · reply within 1–2 working days