Querying Cloud Kit Core Data Record

417 views Asked by At

I have a app that I'm trying to migrate over to using CloudKit to store the core data so it can be synced across devices.

The syncing is working fine, the issue I'm having is that the app adds some initial data to the database, this is causing it to be duplicated when its installed on another device. Currently I'm using user defaults to store a bool locally if the first run has been performed, which obviously only works per device

Is there any way to see if data already exists in the cloud and prevent the addition of the initial data.

Apple's documentation would suggest its possible if an object already exists but on first launch there's no objects in the local store. https://developer.apple.com/documentation/coredata/mirroring_a_core_data_store_with_cloudkit/reading_cloudkit_records_for_core_data

1

There are 1 answers

3
Steve B On

Assuming both devices are using the same CloudKit login then, if the data you want to check is stored on the User record you could do this:

  1. Grab the CloudKit ID for that user
func iCloudUserIDAsync(complete: @escaping (_ instance: CKRecord.ID?, _ error: NSError?) -> ()) {
        let container = CKContainer.default()
        container.fetchUserRecordID() {
            recordID, error in
            
            if let error = error {
               //handle
            } else {
                self.userRecordID = recordID
                complete(recordID, nil)
            }
        }
    }
  1. Then use that ID to query CloudKit at get the user back:
CKContainer.default().publicCloudDatabase.fetch(withRecordID: userRecordID) { (results, error ) in
     if results != nil {
         //got the user record, do what you want with it
     }
     if let error = error {
         //handle error
     }
}

Alternatively, if your data isn't on the user record, then you'll want to do a query using CKQueryOperation and predicates: Good tutorial here: https://www.raywenderlich.com/4878052-cloudkit-tutorial-getting-started