5

I want to use the applicationWillTerminate function to save some user defaults before the app closes. The data I want to save is stored in an EnvironmentObject.

How can I access it from the AppDelegate class?

1
  • You should throw the [SwiftUI] tag on this :) Commented Jun 20, 2019 at 20:21

2 Answers 2

5

An @EnvironmentObject doesn't need to be instantiated directly in your SwiftUI objects; rather, it can be allocated somewhere else (for example, your UISceneDelegate) and then passed through using the .environment(…) function.

You could also allocate it on your AppDelegate, and pass that object though to your views in UISceneDelegate.scene(_:willConectTo:options:) method.

Paul Hudson has a good description of all of this at https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

Sign up to request clarification or add additional context in comments.

2 Comments

In case someone needs code example for this answer. class Test: ObservableObject{ } ------ in appdelegate: class AppDelegate: UIResponder, UIApplicationDelegate { var myVar = Test() } ------ in SceneDelegate: let window = UIWindow(windowScene: windowScene) let myVar = (UIApplication.shared.delegate as! AppDelegate).myVar window.rootViewController = UIHostingController(rootView: contentView.environmentObject(myVar))
@Nalov you should post this as an answer so it's clearly formatted. This was exactly what I needed :)
5

In case someone needs code example for this answer.

1.Create class that conforms to ObservableObject

class Test: ObservableObject{ }

2.in AppDelegate.Swift declare var myVar = Test()

class AppDelegate: UIResponder, UIApplicationDelegate {
    var myVar = Test()

    //****
}

3.in SceneDelegate.swift in "if let windowScene = scene as? UIWindowScene {" change the code like this :

if let windowScene = scene as? UIWindowScene {

    let myVar = (UIApplication.shared.delegate as! AppDelegate).myVar
    window.rootViewController = UIHostingController(rootView: contentView.environmentObject(myVar))
    self.window = window
    window.makeKeyAndVisible()

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.