Display Image From Parse In Swift

1k Views Asked by At

I am trying to display the image I have stored in Buddy For Parse into a UIImageView, however I keep getting this error:

Could not cast value of type 'PFFileObject' (0x1045e0568) to 'NSString' (0x1041d75d8). 2019-04-13 18:15:09.869460-0500 PerfectLaptop[43839:3094232] Could not cast value of type 'PFFileObject' (0x1045e0568) to 'NSString' (0x1041d75d8).

I have already stored numerous strings into Parse, and am able to access them with no problems, and have stored the image I wanted to use also, however no matter what I try, I can't seem to get it to work. Many of the solutions I have found include casting the object as a PFFile, however this doesn't seem to exist anymore.

let query = PFQuery(className: "whichOneRecommended")
query.findObjectsInBackground { (objects, error) in
    if error == nil
    {
        if let returnedobjects = objects
        {
            for object in returnedobjects
            {

                if (object["whichOne"] as! String).contains("\(self.whichOneJoined)")
                {
                    self.laptopImage.image = UIImage(named: (object["laptopImage"]) as! String)



                }
            }
        }
    }
}

While the image file is viewable and downloadable in parse, I can't seem to actually have it be displayed in the imageview, and i want the image view to change programmatically by running this function as I have with other parts of the object.

Thanks in advance

2

There are 2 best solutions below

1
On

guard let imageString = message, let imageURL = URL(string: imageString) else { return }

    do {
let imageData = try Data(contentsOf: imageURL)
    image.image = UIImage(data: imageData)
    } catch {

    }
0
On

The first thing to note is that PFFile has been renamed to PFFileObject.

You are trying to pass object["laptopImage"] which is a value of type Any to UIImage(named:) which can't be done because that function expects a String.

Firstly you need to create a constant of type PFFileObject:

let file = object["laptopImage"] as? PFFileObject

And then download the file data, create a UIImage from the PFFileObject and assign the image to the UIImageView:

file.getDataInBackground { (imageData: Data?, error: Error?) in
    if let error = error {
        print(error.localizedDescription)
    } else if let imageData = imageData {
        let image = UIImage(data: imageData)
        self.laptopImage.image = image
    }
}

Details on this can be found in the section on files in the iOS Guide.