swiftcloudkitckquery

CKQuery with CloudKit Issue


I'm very new to CloudKit and am simply trying to run the most basic query. I want to pull from RecordType "Users" and field type "Name" and have the name equal to my nameText label!

Please see my code below:

 func getUserInformation() {
    let Pred = NSPredicate(value: true)
    let Query = CKQuery(recordType: "Namer", predicate: Pred)
    let AgeOp = CKQueryOperation(query: Query)
    AgeOp.database = self.Pub
    AgeOp.recordFetchedBlock = {(record : CKRecord!) in
        let Recorded : CKRecord = record!
        self.nameText.text = Recorded.objectForKey("Name") as? String
    }
}


override func viewDidLoad() {
    super.viewDidLoad()

    self.Container = CKContainer.defaultContainer() as CKContainer
    self.Pub = Container.publicCloudDatabase as CKDatabase
    self.Container.accountStatusWithCompletionHandler {
        accountStatus, error in
        if error != nil {

            print("Error: \(error?.localizedDescription)")
        } else {
    self.getUserInformation()
        }
    }

}

Solution

  • Users is a system table. You could add new fields to that, but it's advised not to do so. One of the main reasons is that you cannot query the Users recordType.

    Besides that I see in your code that you query the recordType Namer and not Users. Is your question wrong or is your code wrong?

    In the recordFetchedBlock you directly put the result in the .text. That block will be executed in a background thread. You should first go to the mainQueue. You could do that like this:

    AgeOp.recordFetchedBlock = {(record : CKRecord!) in
      NSOperationQueue.mainQueue().addOperationWithBlock { 
        let Recorded : CKRecord = record!
        self.nameText.text = Recorded.objectForKey("Name") as? String
       } 
    }
    

    When there is no query match, then the .recordFetchedBlock will never be called. You should also set the .queryCompletionBlock

    The query could return multiple records (if there are more people with the same name). In the recordFetchedBlock you should add records to an array. Then in the .queryCompletionBlock you could use that array.