Get Newest Record from CloudKit Database

133 Views Asked by At

I'm new to CloudKit (and haven't used NSPredicate much) and am looking to do something which, I'd imagine, is quite basic. I'd like to retrieve the data record with the newest creationDate.

Right now I'm just pulling all the records and scooping up the last one, but there's got to be a more elegant way. Here's my current approach:

let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "NewsItem", predicate: predicate)

CKContainer(identifier: "…").publicCloudDatabase.perform(query, inZoneWith: CKRecordZone.default().zoneID) { result, error in
    let sortedRecords = result.sorted {
        guard let date1 = $0.value(forKey: "creationDate") as? Date,
              let date2 = $1.value(forKey: "creationDate") as? Date else {
            return false
        }
        return date1 < date2
    }

    let item = NewsItem(from: sortedRecords[0])
    …
}

I've used NSPredicate to get a subset of results before, but never max/min style results. Is this possible?

1

There are 1 best solutions below

0
Rogare On

This seems like a step in the right direction:

let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "NewsItem", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

CKContainer(identifier: "…").publicCloudDatabase.perform(query, inZoneWith: CKRecordZone.default().zoneID) { result, error in
    let item = NewsItem(from: result.last)
    …
}

Though I'm still curious if there's a way to simply query by max creationDate…