CloudKit not returning the most recent data
Asked Answered
E

1

16

I am having this issue where I save something to the icloud using CloudKit but immediately fetching the results doesn't return the latest data inserted.

Example

let todoRecord = CKRecord(recordType: "Todos")
todoRecord.setValue(todo, forKey: "todotext")
publicDB.saveRecord(todoRecord, completionHandler: { (record, error) -> Void in
        NSLog("Saved in cloudkit")
        let predicate = NSPredicate(value: true)
        let query = CKQuery(recordType: "Todos",
            predicate:  predicate)

        self.publicDB.performQuery(query, inZoneWithID: nil) {
            results, error in
            if error != nil {
                dispatch_async(dispatch_get_main_queue()) {
                    self.delegate?.errorUpdating(error)
                    return
                }
            } else {
                NSLog("###### fetch after save : \(results.count)")
                dispatch_async(dispatch_get_main_queue()) {
                    self.delegate?.modelUpdated()
                    return
                }
            }
        }

Result :

Before saving in cloud kit : 3
CloudKit[22799:882643] Saved in cloudkit
CloudKit[22799:882643] ###### Count after save : 3

Am I missing something here guys?

Effuse answered 15/10, 2014 at 5:31 Comment(0)
E
20

There is a delay between when a record is saved in CloudKit and when the indexes have been updated with values from that record.

When a CKModifyRecordsOperation completes successfully you are able to immediately fetch that record via its record identifier.

However, there is a delay while the record is added to the search indexes on the server and queries won't find that record immediately.

If you're using a CKQuery to back a view you'll want to keep a side table of records that have been modified locally and stitch those into the view until the query starts returning that record.

Extricate answered 21/2, 2015 at 1:48 Comment(2)
Update the doc link: developer.apple.com/documentation/cloudkit/ckqueryoperation/…Welcy
I discovered this the hard way also. This answer is the best I've seen. However, is there some way to be notified when iCloud has finished its thing or is there some way to CKQuery which will pick up this new record that we know has been saved successfully. I noticed that a CKQuery after a delete works perfectly.Urogenous

© 2022 - 2024 — McMap. All rights reserved.