In SwiftUI 5.1, I want to use AppDelegate to create an userData object. userData will also contain BLE advertisement data, which will be updated from AppDelegate, too. These data should be available to the UI to display those values.
In AppDelegate I use
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private var centralManager : CBCentralManager! var userData: UserData! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. userData = UserData() return true } In SceneDelegate I want to pass to the view using
class SceneDelegate: UIResponder, UIWindowSceneDelegate { @EnvironmentObject var userData: UserData var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Use a UIHostingController as window root view controller if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: BeaconList().environmentObject(userData) ) self.window = window window.makeKeyAndVisible() } } Compiling works fine, but when running the code I get
Thread 1: Fatal error: Reading EnvironmentObject outside View.body
If I remove the
.environmentObject(userData)
I get
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Essentially, I'm trying to make create and update the userData object from AppDelegate, and to display from SceneDelegate and view below.
How can I implement this?
SceneDelegate? This is what Apple is requiring for this sort of thing. (You may have found an outlier case that isn't covered, but I'm doubtful.)userDataeach time a new scene is created?