How do you add .environment(...) to your ContentView() when you don't have a scene delegate (SwiftUI)?

428 Views Asked by At

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)

1

There are 1 best solutions below

0
Asperi On BEST ANSWER

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)
    }