Issues retrieving PFFile from Parse

528 views Asked by At

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
        })


    })

}
2

There are 2 answers

2
Thibaud David On

Your error is probably on saving:

let imageFile = PFFile(name:"image.png", data:imageData)
profilePictures["profilePhoto"] = imageFile
profilePictures.save()

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

0
Syed Tariq On

For some reason you are not getting userImageFile correctly set. It appears to be a nil. I would check the Parse console to confirm that you have an image in the PFile. In any case it may be smarter to use 'if let' to avoid the unwrapping problem. This will not solve the problem if there if PFile is not saved since as pointed below you should use saveInBackground and use notifications to confirm that you are ready for a retrieval.

if 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
    })
}