Search code examples
swiftswiftuinsmanagedobjectcontext

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


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)


Solution

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