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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With