Search code examples
iosxcodecore-dataicloudcloudkit

SwiftUI, CloudKit - Can't Load Core Data NSPersistentCloudKitContainer


I have a fully developed App using Core Data. Now that it is complete, I want to add CloudKit synchronization (like I have done with other apps). However, when I attempt to do so, the loadPersistentStores function fails to load the CloudKit persistent store.

I have added CloudKit Capability and Background Modes Remote Notification.

enter image description here

The Identifier is registered on the Developer site:

enter image description here

I have a singleton CoreDataManager class for the data functions which works just fine with the local store:

class CoreDataManager: ObservableObject {

    static let instance = CoreDataManager()

    @Published var pubSortOrder: String = "lastName"
    //bunch more

    //let container: NSPersistentContainer
    let container: NSPersistentCloudKitContainer
    let context: NSManagedObjectContext

    private init() {
    
        //container = NSPersistentContainer(name: "ResLogCloud")
        container = NSPersistentCloudKitContainer(name: "ResLogCloud")
        container.loadPersistentStores { (description, error) in
            if let error = error {
                print("Error loading Core Data. \(error.localizedDescription)")
            }
        }
    
        context = container.viewContext
        //uncomment next for CloudKit container
        context.automaticallyMergesChangesFromParent = true
        context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    
    }//init

    //bunch of functions dealing with data

}//class

Just for grins, I have reset the environment in CloudKit Dashboard a couple of times.

The console error simply says "Error loading Core Data. A Core Data error occurred." Obviously, that is not very helpful.

I'm out of ideas. Any guidance would be appreciated. Xcode 13.2.1 iOS 15.


Solution

  • This is weird. I discovered that I had marked one Core Data attribute as not-optional but I had not provided a default value. Once I provided the default value the CloudKit store worked as expected. As you would expect, it was a rather complicated debug process to find this.

    There are launch codes that can be used to find additional Core Data debug info - I did not find one to help me in this situation, though I believe there is one. For others, you could start here:

    https://developer.apple.com/documentation/coredata/accessing_data_when_the_store_changes

    Again, the local persistent store did not seem to care about this not-optional value, but the persistent CloudKit store did.