CloudKit: order query results by creation date

When downloading items from CloudKit, I want to order the results by the creation date. In my opinion, now it is sorted by the first record property.

func loadItems() { let predicate = NSPredicate(value: true) let query = CKQuery(recordType: "Items", predicate: predicate) db.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in if error != nil { println(error.localizedDescription) } dispatch_async(dispatch_get_main_queue()) { () -> Void in items = results as [CKRecord] self.tableView.reloadData() println("items: \(items)") } } } 
+7
ios swift icloud cloudkit
source share
4 answers

That's what I was looking for:

 query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] 
+15
source share

Here is the Objective-C solution. It works similarly in Swift.

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"TRUEPREDICATE"]; CKDatabase *privateDatabase = [self.myContainer privateCloudDatabase]; CKQuery *query = [[CKQuery alloc] initWithRecordType:@"command" predicate:predicate]; query.sortDescriptors = [NSArray arrayWithObject:[[NSSortDescriptor alloc]initWithKey:@"creationDate" ascending:true]]; 

However, you may receive the following error message:

CKError 0x12e874f10: "Invalid Arguments" (12/2016); server message = "Field" ___createTime "is not marked sortable"; uuid = 468AC2A4-24D6-4A56-81BB-6A2A8027DC15; container ID = "iCloud.com.xxx"

So, just make it sorted in the toolbar: enter image description here

+11
source share

Swift - 3.0

 let recordInsertDate = records["creationDate"]! print("recordInsertDate : \(recordInsertDate)") let query = CKQuery(recordType: "className", predicate: NSPredicate(format: "creationDate >= %@ " , recordInsertDate as! CVarArg)) 
0
source share

You can use NSPredicate. You were right.

 let startDate = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate()) let predicate = NSPredicate(format: "creationDate > %@", startDate) 

But you need to include the createDate field in the CloudKit field so that you can use them in the request.

-one
source share

All Articles