Home > Net >  How do you add .environment(...) to your ContentView() when you don't have a scene delegate (Sw
How do you add .environment(...) to your ContentView() when you don't have a scene delegate (Sw

Time:08-21

Normally when you create a new swiftUI app, you have this scene delegate:

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

and you have your contentView:

struct ContentView: View {}

I would like to add .environment to contentView as follows:

ContentView()
.environment(\.managedObjectContext, yourCoreDataContext)

But as I initially created my app as a swift UIKit app I don't have this scene delegate to do this. How can I add the environment?

(I am using UIHostingController to show my swiftUI view)

CodePudding user response:

If you created UIKit project with CoreData then view context is in AppDelegate, so the code of presenting controller with ContentView might look like

    if let delegate = UIApplication.shared.delegate as? AppDelegate {
        let viewContext = delegate.persistentContainer.viewContext
        let controller = UIHostingController(rootView:
            ContentView()
            .environment(\.managedObjectContext, viewContext)
        )
        self.present(controller, animated: true)
    }
  • Related