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
  • 2,999
  • 9
  • 46
  • 72

4 Answers4

23

This is what I was looking for:

query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
colindunn
  • 2,999
  • 9
  • 46
  • 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

vomako
  • 8,350
  • 5
  • 34
  • 59
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,057
  • 2
  • 27
  • 37
-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,099
  • 9
  • 78
  • 104
  • 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