Search code examples
ioscloudkitswift5

Querying a range of data with CloudKit in iOS


I'm new to CloudKit and swift. I have a query that successfully pulls all my records and sorts them by creationDate (below). However, I want to be able to pull the first 10 records by creationDate. Then have a button to load the next 10 and so on. I've been doing some searching, but getting nowhere. Any help would be greatly appreciated!

        stream = [CKRecord]()
        let publicData = CKContainer.default().publicCloudDatabase
        let query = CKQuery(recordType: "myRecords", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
        query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        publicData.perform(query, inZoneWith: nil) { (results:[CKRecord]?, error:Error?) -> Void in
        if let stream = results {
            self.stream = stream
            DispatchQueue.global(qos: .background).async {
                DispatchQueue.main.async {
                    for record in stream {
//                        Do stuff here
                        }
                    }
                }
            }
        }
    }

Solution

  • CKQuery has property resultsLimit.

    You can specify number of records to be returned.

    Edit:

    Apple documentation