Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow response time from CloudKit APIs?

Tags:

swift

cloudkit

I have made a simple app for interacting with a CloudKit database. Essentially it's just a date picker and two buttons, the first adding a new record with the set time to the database, and the second retrieving all the records. This seems to work fine except that all operations are extremely slow. It takes around 10 seconds to get a response from both saveRecord and performQuery. What am I doing wrong? Below is the code from retrieving records.

@IBAction func retreiveButtonClick(sender: AnyObject) {
    self.labelOutlet.text = "Waiting..."

    func myHandler(results:[AnyObject]!, error:NSError!) {
        if let err = error {
            println("err: \(err.localizedDescription)")
        } else {
            self.labelOutlet.text = "Got \(results.count) results:"
            for record in results {
                let time = record.objectForKey("testTime") as NSDate
                self.labelOutlet.text = self.labelOutlet.text + "\n\(time.description)"
            }
        }
    }

    var query = CKQuery(recordType:"TestTable", predicate:NSPredicate(value:true))
    cloudDatabase.performQuery(query, inZoneWithID: nil, myHandler)   
}

I am testing this on my iPhone 5, which is connected to the local WiFi. I have noticed that saved records show up in CloudKit Dashboard long before the completion handler is called (which I have plenty of time to check), so I suspect I have done something wrong in my code.

like image 516
pc3e Avatar asked Aug 28 '14 18:08

pc3e


2 Answers

Your handler will be called in a background thread. You should perform all UI manipulations on the main thread. You could put all your myHandler code within a block like:

func myHandler(results:[AnyObject]!, error:NSError!) {
NSOperationQueue.mainQueue().addOperationWithBlock({
        // ... put here your function code.
    })
}

It could be that other code is executing on the main queue that could hold up execution of this code. Make sure you execute long lasting code on a background queue.

Besides that there is nothing wrong with your code.

like image 82
Edwin Vermeer Avatar answered Sep 23 '22 04:09

Edwin Vermeer


Adding to Edwin's answer...

I agree it looks like you are trying to update the UI on a background thread.

If you want to avoid the NSOperationQueue complexity...you could...in ObjectiveC

dispatch_async(dispatch_get_main_queue(), ^{
     //...update code 
});
like image 23
Bill Johnson Avatar answered Sep 21 '22 04:09

Bill Johnson