Search code examples
iosswiftcloudkit

How to use "fetchWithRecordID" for automatically generated ID in CloudKit Dashboard?


I'm new to CloudKit and iOS development. I've manually added some records to the CloudKit Dashboard, and now I want to retrieve them by their IDs, which were automatically created. And then I want to display a record's value in a UILabel for a static tableview cell. Having two issues: 1). I'm getting an error in xCode when using the ID from the dashboard (error says "expected "," separator") ; and 2). I can't find any examples of putting a record value in a UILabel in a static tableview cell. (especially for swift). Any help is greatly appreciated!

Here's my code:

override func viewDidLoad() {
    super.viewDidLoad()

    publicDB.fetchRecordWithID (f7080e7a-f8c3-4db6-b8ee-642a011a6762) { record, error in


        if error != nil {

            println("there was an error \(error)")

        } else {

            // this is my UILabel in a static tableview. The record's only attribute is //called "subCategory"

            plasticOneValue.text = record["subCategory"]
        }   
    }
}

UPDATE: ALTERNATIVELY - I tried this code and the build succeeded, but console said it had an internal error and the UILabel was still blank......Any suggestions on what I'm doing wrong with the above code or this code?

override func viewDidLoad() {
    super.viewDidLoad()

    // I created a new CKRecord ID Object and provided the existing ID in dashboard and //it fixed the error about requiring a "," separator

   var plasticOneID = CKRecordID(recordName: "f7080e7a-f8c3-4db6-b8ee-642a011a6762")

    publicDB.fetchRecordWithID (plasticOneID) { record, error in

        if error != nil {

            println("there was an error \(error)")

        } else {

            self.plasticOne.text = (record.objectForKey("subCategory") as String)

        }
    }
}

Solution

  • These are 2 different issues

    1. when querying an ID, you have to query for a CKRecordID as you did in the 2nd sample
    2. When accessing the UI, you have to do that on the main queue.

    So then the code would be something like:

    publicDB.fetchRecordWithID(CKRecordID(recordName: "f7080e7a-f8c3-4db6-b8ee-642a011a6762"), completionHandler: {record, error in
        if error != nil {
            println("there was an error \(error)")
        } else {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                self.plasticOne.text = (record.objectForKey("subCategory") as String)
            }
       }
    })