Slow response time from CloudKit API?

I created a simple application to interact with the CloudKit database. In fact, this is only a date selection and two buttons, the first is the addition of a new record with a set time to the database, and the second is the extraction of all records. This seems to work just fine, except that all operations are very slow. It takes about 10 seconds to get a response from saveRecord and performQuery. What am I doing wrong? Below is the code to restore 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 local Wi-Fi. I noticed that saved records are displayed in CloudKit Dashboard long before the completion handler is called (I have enough time to check), so I suspect that I did something wrong in my code.

+7
swift cloudkit
source share
2 answers

Your handler will be called in the background thread. You must perform all user interface manipulations in the main thread. You can put all your myHandler code in a block, for example:

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

It is possible that other code is running in the main queue, which may delay the execution of this code. Make sure you run long code in the background.

Also, there is nothing wrong with the code.

+6
source share

Adding back to Edwin ...

I agree, it looks like you are trying to update the user interface in the background thread.

If you want to avoid the complexity of NSOperationQueue ... you can ... in ObjectiveC

 dispatch_async(dispatch_get_main_queue(), ^{ //...update code }); 
+3
source share

All Articles