Check if data exists in cloud kit

My App does some importing when its first setup. I have it set to store core data in cloud kit.

My issue is if you run it on one device, everything imports fine. Run it on a second, and it will import for a second time, duplicating the records.

I'm trying to see if there's a way of checking if there is anything in cloud kit before running the import, but I'm always getting back false, even if I know there are records.

The code I'm using to check is

NSLog("Existance Check")
        checkIfExistsInCloudKit() { (result) in
            print(result)
            if result == false {
                NSLog("Does Not Exist")
                //let ImportData : ImportData = ImportData(viewContext: viewContext)
                //ImportData.importAll()
            } else {
                NSLog("Does Exist")
            }
        }
        NSLog("Existance Check Complete")

and the function is

func checkIfExistsInCloudKit(_ completion: @escaping (Bool) -> ()) {
    var result = false
    
    let container = CKContainer(identifier: "******")
    let privateDB = container.privateCloudDatabase
    let predicate = NSPredicate(format: "CD_brand = %@", "DMC")
    let query = CKQuery(recordType: "CD_Colour", predicate: predicate)
    privateDB.perform(query, inZoneWith: nil) { records, error in
       //guard let records = records else { return }
        result = true
    }
    
    completion(result)
}

2023-04-15 14:07:28.092262+0100 Stitchers Companion[4553:113693] Existance Check

false

2023-04-15 14:07:28.092897+0100 Stitchers Companion[4553:113693] Does Not Exist

2023-04-15 14:07:28.092962+0100 Stitchers Companion[4553:113693] Existance Check Complete

Post not yet marked as solved Up vote post of Desbrina Down vote post of Desbrina
554 views
  • I'm having this exact same issue. Did you happen to discover a solution that you can share? My SwiftData app does the initial setup of the DB fine on one device but when installing on a second device the data comes back as empty, but is actually syncing in the background. If I knew what exactly what was happening with events I could put up a "synchronizing with icloud" modal or something. And if not data already exists, go ahead and create a demo database and update the UI. Thanks for any help.

Add a Comment