0

I'm working with CloudKit for the first time and am having trouble executing a CKQueryOperation to query all records of a given type. It doesn't help that Apple has deprecated most of the stuff I've found online and that their documentation for these things are completely blank besides the func declaration. I think I've got the "skeleton" of the code done but am unsure of what goes into the .recordMatchedBlock and the .queryResultsBlock.

I have a func queryAllNotes() which should query all records in the public database of type "Notes" and return an array of tuples of the note's title and its associated cloudID, which is just the unique recordName given to it when it is added to the database.

Here's the code for queryAllNotes() :

private func queryAllNotes() -> [(title: String, cloudID: String)] {
    /*
     query all notes in the cloud DB into an array to populate
     the tableView
     */
    var resultArray: [(title: String, cloudID: String)] = []
    
    //set the cloud database to .publicCloudDatabase
    let container = CKContainer.default()
    let cloudDB = container.publicCloudDatabase
    
    
    let pred = NSPredicate(value: true) //true -> return all records
    let query = CKQuery(recordType: "Notes", predicate: pred)
    let queryOperation = CKQueryOperation(query: query)
    queryOperation.database = cloudDB
    queryOperation.resultsLimit = 100
    
    queryOperation.recordMatchedBlock = { (record: CKRecord) in
        let noteTitle = record["Title"] as! String
        let noteCloudID = record.recordID.recordName
        
        resultArray.append((noteTitle, noteCloudID))
    }
    
    queryOperation.queryResultBlock = { (cursor, error) in
        
        
    }
    
    return resultArray
}

To my understanding the .recordMatchedBlock is called for every record returned by the query so I think it is complete but I could be very wrong. In regards to the .queryResultBlock, my understanding is that the query technically only return one record at a time and this block basically tells the query to run again for the next record for all records within the .resultLimit. How can I structure this query? I am keen to understand what each of these blocks do.

Also this is for a macOS app; I don't know if the code is different for macOS vs iOS but I thought I should include this just in case.

Also I'm getting an error saying "Type of expression is ambiguous without more context" which I'm assuming is because I haven't completed setting up my query. If it's for a different reason could also explain why this is happening.

Edit

I call this func inside of viewDidLoad() like so:

//array var for the array that is used to populate the tableView
var noteRecords: [(title: String, cloudID: String)] = []

override func viewDidLoad() {
    super.viewDidLoad()
    
    // do additional setup here
    
    // set serachField delegate
    searchField.delegate = self
    
    // set tableView delegate and data source
    tableView.delegate = self
    tableView.dataSource = self
    
    // load all NoteRecords in public cloud db into noteRecords
    
    noteRecords = queryAllNotes()
    
}
8
  • 1
    You are mixing up an async signature with asynchronous API in a synchronous context. You cannot use both simultaneously. Either use new async/await or add a completion handler.
    – vadian
    Mar 18, 2022 at 15:17
  • @vadian I'm a bit confused on what you're saying so could you check the edit where I added where I call queryAllNotes() inside of viewDidLoad() this is my first time using cloudKit and async funcs so if you could provide an answer on how to structure the CKqueryOperation inside the func and how to call it inside of viewDidLoad() that would be very helpful. Mar 18, 2022 at 15:46
  • @vadian I took out the async tag, which I think was still there from a previous version of that func that I wrote which didn't work, so I think I just need to structure the CKQueryOperation correctly now, I also edited the question to reflect my current code Mar 18, 2022 at 15:50
  • It still might be necessary to use CKQueryOperation sometimes, until we get full async API replacements, but I don't see you needing anything more than the most common use case. As such, I don't really think this question is about CKQueryOperation. stackoverflow.com/questions/71200053/…
    – Jessy
    Mar 18, 2022 at 16:03
  • @Jessy I saw that post earlier and was a bit confused by the code so could you please explain it a bit so that I know how to properly use it in order to populate my noteRecords array? Sorry if it's a dumb question this is my first time working with cloudKit and I'm a bit lost Mar 18, 2022 at 16:07

1 Answer 1

2

With the new async pattern it has become much easier to fetch data from CloudKit.

Instead of CKQueryOperation you call records(matching:resultsLimit:) directly and map the result to whatever you like.

A possible error is handed over to the caller.

func queryAllNotes() async throws -> [(title: String, cloudID: String)] {
    //set the cloud database to .publicCloudDatabase
    let container = CKContainer.default()
    let cloudDB = container.publicCloudDatabase
    
    let pred = NSPredicate(value: true) //true -> return all records
    let query = CKQuery(recordType: "Notes", predicate: pred)
    
    let (notesResults, _) = try await cloudDB.records(matching: query,
                                                        resultsLimit: 100)
    return notesResults
        .compactMap { _, result in
            guard let record = try? result.get(),
                    let noteTitle = record["Title"] as? String else { return nil }
            return (title: noteTitle, cloudID: record.recordID.recordName)
        }
}

And use it

override func viewDidLoad() {
    super.viewDidLoad()
    
    // do additional setup here
    
    // set serachField delegate
    searchField.delegate = self
    
    // set tableView delegate and data source
    tableView.delegate = self
    tableView.dataSource = self
    
    // load all NoteRecords in public cloud db into noteRecords
    Task {
       do {
          noteRecords = try await queryAllNotes()
          tableView.reloadData()
       } catch {
          print(error)
       } 
    }
    
}

Please watch the related video from WWDC 2021 for detailed information about the async CloudKit APIs and also the Apple examples on GitHub.

Side note:

Rather than a tuple use a struct. Tuples as data source array are discouraged.

5
  • I'm now trying to modify this func to work for custom zones within a private database and was wondering if you could take a look at this question here Mar 29, 2022 at 17:16
  • You can create multiple zones in the private database with modifyRecordZones(saving:deleting:)
    – vadian
    Mar 29, 2022 at 18:46
  • I've already created the zones in the private database, and placed some pre populated data in them to test it out, I'm more wondering how I would modify this func you've provided to work on a specific zone within the private database. If I'm completely missing the mark I would more than appreciate a detailed explanation on the question I have linked Mar 29, 2022 at 19:32
  • Please read the documentation of CKDatabase. There are many APIs which have a record zone parameter. This parameter can be omitted if the default zone is being addressed.
    – vadian
    Mar 29, 2022 at 19:41
  • I tried using .records(matching: , inZoneWith: ) and when I debug the code the session ends when it reaches that line. I'm now trying to use fetch(withQuery: , inZoneWith: ) but am unsure of how to write the completion handler since there is no documentation for this func. If you could please provide some insight on either why the .records func is not executing correctly or how to set up the completion handler for the .fetch func that you be very much appreciated. Mar 29, 2022 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.