I am creating an app in parse in which the user has an option to choose a profile picture when they sign up. This is the code for that.
var profilePictures = PFObject(className: "ProfilePictures")
let imageData = UIImagePNGRepresentation(self.profileImage.image)
let imageFile = PFFile(name:"image.png", data:imageData)
profilePictures["profilePhoto"] = imageFile
profilePictures["user"] = usernameField.text
profilePictures.save()
Later I have a screen in which a UIImageView needs to be populated with the chosen profile picture.
This works until the application itself is stopped completely and restarted.
The PFFile is then found as nil and I get the error "unexpectedly found nil while unwrapping an optional value".
Here is the code for displaying the picture.
override func viewDidAppear(animated: Bool) {
var query = PFQuery(className: "ProfilePictures")
query.whereKey("user", equalTo: PFUser.currentUser()?.username)
query.findObjectsInBackgroundWithBlock({
(success, error) -> Void in
let userImageFile = profilePictures["profilePhoto"] as! PFFile
//error is on the above line
userImageFile.getDataInBackgroundWithBlock({
(imageData: NSData?, error) -> Void in
var image = UIImage(data: imageData!)
self.profileImage.image = image
})
})
}
Your error is probably on saving:
You are saving an object with a pointer to a new unsaved PFFile, which leads to error. You should first do imageFile.saveInBackground, and use callback to assign imageFile on profilePictures, then save profilePictures.
You can confirme that by seeing on Parse's datastore that there is no value for key 'profilePhoto' on your profilePictures object