0
votes

I have had lots of initial success saving and querying records in CloudKit. Now I am stuck on something easy. For each user, I want to save his CloudKit user ID so they can view a list of their saved records.

I thought that the completionHandler provided the saved record, populated with useful meta info. This is the start of my completionHandler func:

func recordSaved(record: CKRecord?, error: NSError?) {

        if (record != nil) {
            var myUserRecordID:CKRecordID = record!.creatorUserRecordID
            let UserRecordIDToStore = NSKeyedArchiver.archivedDataWithRootObject(myUserRecordID)
            plist.setValue(UserRecordIDToStore, forKey: "lastCKRecordID")
        }

It is called when this save action is finished:

publicDatabase.saveRecord(newRecord, completionHandler: recordSaved)

However, in the first line after the if (starting with "var ...") I received the following error message: "fatal error: unexpectedly found nil while unwrapping an Optional value". I don't understand why this is nil.

Please help: 1. Explain what I am doing wrong 2. Any tips on saving the user ID for future query use.

Thanks!

1

1 Answers

0
votes

Never mind. Here is the answer (just use it as stand alone code):

CKContainer.defaultContainer().fetchUserRecordIDWithCompletionHandler({ userRecordID, error in
            if error == nil {
                let UserRecordIDToStore = NSKeyedArchiver.archivedDataWithRootObject(userRecordID)
                plist.setValue(UserRecordIDToStore, forKey: "userCKRecordID")
                println("User identified as: \(userRecordID.description)")
            } else {
                println("Can not identify user due to error: \(error.localizedDescription)")
            }
        })