Contents

Central Manager State Restoration Options

Restore central manager state in scene-based apps.

Overview

In scene-based apps that adopt UISceneDelegate, the launchOptions dictionary is always nil on launch, and apps can no longer rely on the system to hand back central manager identifiers at launch.

Instead, generate a stable UID for each CBCentralManager, persist it (for example, in UserDefaults) and pass it via CBCentralManagerOptionRestoreIdentifierKey when creating the manager on every launch. When restoration is available, Core Bluetooth calls centralManager(_:willRestoreState:) and passes the preserved state in the dict parameter.

func makeCentralManager(
    delegate: any CBCentralManagerDelegate
) -> CBCentralManager {
    let defaults = UserDefaults.standard
    let key = "MyCentralManagerUID"
    let uid: String
    if let saved = defaults.string(forKey: key) {
        uid = saved
    } else {
        uid = UUID().uuidString
        defaults.set(uid, forKey: key)
    }
    return CBCentralManager(
        delegate: delegate,
        queue: nil,
        options: [CBCentralManagerOptionRestoreIdentifierKey: uid]
    )
}

CBCentralManagerRestoredStatePeripheralsKey contains peripherals that were connected or had a pending connection when the app stopped. CBCentralManagerRestoredStateScanServicesKey contains the service UUIDs your app was scanning for. CBCentralManagerRestoredStateScanOptionsKey contains the scan options that were active. If your app also acts as a peripheral, see Peripheral Manager State Restoration Options for the equivalent pattern using CBPeripheralManagerOptionRestoreIdentifierKey.

Topics

State Restoration Options

See Also

Initializing a Central Manager