I have currently got CloudKit set up in my app so that I am adding a new record using the help of the following code below,
CKRecordID *recordID
The followig function will return ALL records for requested record type:
let database = CKContainer(identifier: "container_here").privateCloudDatabase
typealias RecordsErrorHandler = ([CKRecord], Swift.Error?) -> Void
func fetchRecords(forType type: String, completion: RecordsErrorHandler? = nil) {
var records = [CKRecord]()
let query = CKQuery(recordType: type, predicate: NSPredicate(value: true))
let queryOperation = CKQueryOperation(query: query)
queryOperation.zoneID = CloudAssistant.shared.zone.zoneID
queryOperation.recordFetchedBlock = { record in
records.append(record)
}
queryOperation.queryCompletionBlock = { cursor, error in
self.fetchRecords(with: cursor, error: error, records: records) { records in
completion?(records, nil)
}
}
database.add(queryOperation)
}
private func fetchRecords(with cursor: CKQueryCursor?, error: Swift.Error?, records: [CKRecord], completion: RecordsHandler?) {
var currentRecords = records
if let cursor = cursor, error == nil {
let queryOperation = CKQueryOperation(cursor: cursor)
queryOperation.recordFetchedBlock = { record in
currentRecords.append(record)
}
queryOperation.queryCompletionBlock = { cursor, error in
self.fetchRecords(with: cursor, error: error, records: currentRecords, completion: completion)
}
database.add(queryOperation)
} else {
completion?(records)
}
}