Search code examples
iosswiftcloudkit

cloudkit saverecord method makes app crash


fyi, i'm following this tutorial

The following method crashes my app in the simulator and a device (5S). The crashes happens at the "publicDatabase!" line.

I get the following generic error

fatal error: unexpectedly found nil while unwrapping an Optional value

@IBAction func saveRecord(sender: AnyObject) {

    if (photoURL == nil) {
        notifyUser("No Photo", message: "Use the Photo option to choose a photo for the record")
        return
    }

    let asset = CKAsset(fileURL: photoURL!)

    let myRecord = CKRecord(recordType: "Houses")
    myRecord.setObject(addressField.text, forKey: "address")
    myRecord.setObject(commentsField.text, forKey: "comment")
    myRecord.setObject(asset, forKey: "photo")

    publicDatabase!.saveRecord(myRecord, completionHandler:
        ({returnRecord, error in
            if let err = error {
                self.notifyUser("Save Error", message:
                    err.localizedDescription)
            } else {
                dispatch_async(dispatch_get_main_queue()) {
                    self.notifyUser("Success",
                        message: "Record saved successfully")
                }
                self.currentRecord = myRecord
            }
        }))
}

Can anyone provide assistance?


Solution

  • The issue is with publicDatabase it'll be nil because probably you didn't initialized it.

    In the code provided there is no relevant code with publicDatabase initialization. So verify that you initialized it before using.