13

When loading items from CloudKit I would like to order the results by creation date. I believe now it's sorting by the first property of the record.

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)")
        }
    }
}
colindunn
  • 3,139
  • 10
  • 48
  • 72

4 Answers4

24

This is what I was looking for:

query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
colindunn
  • 3,139
  • 10
  • 48
  • 72
19

Here is an 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]];

With this, you may get 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 sortable in dashboard: enter image description here

John
  • 8,468
  • 5
  • 36
  • 61
0

Swift - 3.0

let recordInsertDate = records["creationDate"]!
print("recordInsertDate : \(recordInsertDate)")
let query = CKQuery(recordType: "className", predicate: NSPredicate(format: "creationDate >= %@ " , recordInsertDate as! CVarArg))
Community
  • 1
  • 1
Vishal Vaghasiya
  • 4,618
  • 3
  • 29
  • 40
-1

You can use NSPredicate. You were right.

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

But you have to enable the creationDate-field in the CloudKit for querying so that you can use them in a query.

Christian
  • 22,585
  • 9
  • 80
  • 106
  • Hm, I must be doing something wrong. It's still ordering by another property. I enabled both query and sort for the 'Date Created' Metadata indexes. – colindunn Feb 01 '15 at 21:17
  • Yeah, first two lines look like this: `let startDate = NSDate(timeInterval: -60.0 * 120, sinceDate: NSDate()) let predicate = NSPredicate(format: "creationDate > %@", startDate)` – colindunn Feb 01 '15 at 21:19
  • (I assume `date` was meant to be `startDate` in your code above) – colindunn Feb 01 '15 at 21:19