I'm trying to listen for my Bluetooth device in the background, but nothing seems to be happening. I tried following this guide here and modifying it for SwiftUI.
I enabled the bluetooth-central background mode.
I opt In to State Preservation and Restoration.
let options = [CBCentralManagerOptionRestoreIdentifierKey : "myCentralManagerIdentifier"]
centralManager = CBCentralManager(delegate: self, queue: nil, options: options)
I added Restoration Delegate Method. This method gets called when I first run the app again.
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
guard let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] else {
return
}
for peripheral in peripherals {
// ...
}
}
The step for launch options doesn't seem to work for me. The launchOptions dictionary is always nil for me.
import SwiftUI
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
guard let options = launchOptions else {
return true
}
let centralManagerIdentifiers = options[UIApplication.LaunchOptionsKey.bluetoothCentrals]
return true
}
}
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}