'Couldn't initialize CloudKit schema because no stores in the coordinator are configured to use CloudKit

I'm getting this error when trying to initialize the Cloudkit schema:

Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Couldn't initialize CloudKit schema because no stores in the coordinator are configured to use CloudKit: ()}

This is my code:

private lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentCloudKitContainer(name: self.objectModelName)
        
        // Create a store description for a CloudKit-backed local store
        let cloudStoreLocation = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("iCloud.sqlite")
        let cloudStoreDescription = NSPersistentStoreDescription(url: cloudStoreLocation)
        cloudStoreDescription.configuration = "iCloud"

        // Set the container options on the cloud store
        cloudStoreDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.myname.app")
        
        // Update the container's list of store descriptions
        container.persistentStoreDescriptions = [
            cloudStoreDescription
        ]
        
        do {
            try container.initializeCloudKitSchema()
        } catch {
            print(error)
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

This is my: project configuration

This is my: data model schema

Can you anyone help me spot what I'm doing wrong?

Thanks!



Solution 1:[1]

To whom may come across this later. I had the same error and the issue was same as the sample code above.

I called

container.initializeCloudKitSchema()

before calling

container.loadPersistentStores

You will need to instead call container.initializeCloudKitSchema after calling container.loadPersistentStores

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shunny Bunny