Using Core Data with SwiftUI App Protocol

This thread has been locked. Questions are automatically locked after two months of inactivity, or sooner if deemed necessary by a moderator.
Is it possible to use CoreData with the newly announces SwiftUI App Protocol for 100% SwiftUI apps. If I need to create an app with persistant storage, is there a way to achieve this with the new protocol? I like the idea of having my app fully compatable across all systems.

Thanks.
Up vote post of santiago.gs
6.9k views

Solved Answer

Yes, you can setup everything you need directly in your App as following:

Code Block swift
@main
struct SampleApp: App {
    @Environment(\.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
            MovieList()
                .environment(\.managedObjectContext, persistentContainer.viewContext)
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("active")
            case .inactive:
                print("inactive")
            case .background:
                print("background")
                saveContext()
            }
        }
    }
    var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "SampleApp")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    func saveContext() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

34 Replies

Yes, you can setup everything you need directly in your App as following:

Code Block swift
@main
struct SampleApp: App {
    @Environment(\.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
            MovieList()
                .environment(\.managedObjectContext, persistentContainer.viewContext)
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("active")
            case .inactive:
                print("inactive")
            case .background:
                print("background")
                saveContext()
            }
        }
    }
    var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "SampleApp")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    func saveContext() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

Thanks @mtsrodrigues I also was trying to find out how to use CoreData with a Pure Cross-platform SwiftUI App
Is it also possible to implement CoreData Integration with iCloud, like its provided by the standard Xcode templates?
@mtsrodrigues is there any more documentation on this? I don't quit understand all of what's going on in your example. Where is it defining the CoreData store? How do you save after certain actions?
@keelay The store is being created lazily - when it's injected into the environment. As far as saving after certain actions, you can use the MOC in SwiftUI just as you would in a UIKit or AppKit app. This example also saves when the scene goes into the background state.
@micho2, to achieve CloudKit integration you should be able to change the persistentContainer property like so...

Code Block
    var persistentContainer: NSPersistentContainer = {       
let container = NSPersistentCloudKitContainer(name: "SampleApp")      // change this line 
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {               
fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
container.viewContext.automaticallyMergesChangesFromParent = true // add this line
        return container
    }()

although I've not tested this yet!
Super helpful @mtsrodrigues. Is it possible to abstract the persistent container behind a store class that handles adding new items, saves, deletes, etc., and pass that into the environment and update the UI based on changes to the store? I've been trying to make such a thing work with SwiftUI, but have so far been running into lots of roadblocks (but it's probably more my lack of experience with CoreData, than anything else).
Thank you. It can be useful to show its integration into Xcode templates by @Apple!
Using this info that has been provided, what do I need to add to the view that should be saving the data to Core Data

Is it still
Code Block
@Environment(\.managedObjectContext) var moc


I’m also interested in learning how to put this into a store class which is storing to Core Data behind the scenes. I have this working myself, but I’m not sure it’s the right way to do it and it’d be great to follow the lead of someone more experienced and/or Apple.
@ryanbdevilled I'm doing that with singleton pattern (in order to access to persistent store from UIKit views).

Code Block
final class PersistentStore {
let shared = PersistentStore()
lazy var persistentStore = { ... }
func saveContext() { ... }
}


Code Block
var body: some Scene {       
WindowGroup {           
MovieList()
.environment(\.managedObjectContext, PersistentStore.shared)
}
}


It is important to call to PersistentStore.shared from anywhere in your app (because it is instantiated yet), not PersistentStore(). If you are calling that from SwiftUI views, obviously you can directly from @environmentObject.


Regarding  mtsrodrigues's solution, how would one get to the viewContext property elsewhere in the app?

I'm asking because I want to be able to run a preview but don't know what to give to the PreviewProvider. You can't use (UIApplication.shared.delegate as! AppDelegate).persistentContainer because there isn't an app delegate in this case.

And if you do use an app delegate, you have to be calling UIApplication, which means you lose cross-platform Mac support, or you have to do an @available dance, I guess?
@davextreme You don't need AppDelegate to instantiate the persistentContainer in SwiftUI, as he explained. And in my last response you can get the solution for get viewContext working elsewhere in your app (with singleton pattern).
A warning about a mistake in mtsrodrigues's answer. It will recreate the persistent container every time the struct is recreated. Instead you are supposed to use @StateObject to prevent this.
Thanks @AlbertUI. If I'm understanding your code correctly you're putting the entire PersistentStore class singleton instance into the managedobjectcontext key path, as opposed to only the context?

So I assume you can have all manner of helper methods in your PersistentStore class and call those through persistentStore.shared.saveNewObject(), persistentStore.shared.fetchObjects(named: "foo"), etc?

When I was playing around earlier, I was only storing the context under the managedobjectcontext key path, but I never thought it would be possible to put the whole wrapper class into the key path...