Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using core data in a swiftUI view presented from a primarily swift project

Is it possible to use Core Data in a SwiftUI view that’s largely a Swift project? I ask because when I try to get the managed object context from my Swift project into my SwiftUI view all examples are saying it needs to be set first on the top level SwiftUI view like this:

WindowGroup {
    ContentView()
        .environment(\.managedObjectContext, DataController.shared.container.viewContext)
        .environmentObject(coreDataViewModel)
}

Unfortunately, I don’t have a top-level SwiftUI view so this is causing problems. Is there another way to set the MOC on the SwiftUI view or am I going to have to nest my initial Swift view inside a SwiftUI view in order to use Core Data?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes you can mix UIKit and SwiftUI or any other interface.

Swift is the language they share.

“Top level” can be the first SwiftUI view

AnySwiftUIView()
    .environment(\.managedObjectContext, DataController.shared.container.viewContext)

Note that you can also use @ObservedObject To monitor any CoreData object that is passed in as an argument.

You only have to put it in an environment if the views need to access it.

Use SwiftUI with UIKit

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading