Loading an image in Swift from Parse
I am successfully fetching data from Parse in swift, but my images don't seem to work the way I do.
In my cellForRowAtIndexPath method, I do the following:
var event: AnyObject? = eventContainerArray[indexPath.row]
if let unwrappedEvent: AnyObject = event {
let eventTitle = unwrappedEvent["title"] as? String
let eventDate = unwrappedEvent["date"] as? String
let eventDescription = unwrappedEvent["description"] as String
let eventImage = unwrappedEvent["image"] as? UIImage
println(eventImage)
if (eventImage != nil){
cell.loadItem(date: eventDate!, title: eventTitle!, description: eventDescription, image: eventImage!)}
else {
let testImage: UIImage = UIImage(named: "test-image.png")!
cell.loadItem(date: eventDate!, title: eventTitle!, description: eventDescription, image: testImage )
}
}
}
return cell
}
I am using println () with my PFQuery and I see this as part of the object that is being loaded into: image = "<PFFile: 0x7fee62420b00>";
So I get the title, date, description, etc., all are loaded fine as part of the above eventContainerArray, but when I look at the eventImage, it's a nickname every time. The above code always loads test-image.png by default as the image approaches zero. Am I just running this PFFile in the wrong way? Not sure why it doesn't work.
Thank!
source to share
Yours is image
most likely the target PFFile
. You will need to load it to get the object from it UIImage
.
let userImageFile = unwrappedEvent["image"] as PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData!, error: NSError!) -> Void in
if error == nil {
let eventImage = UIImage(data:imageData)
// do something with image here
}
}
source to share
I'm not familiar with Parse, but given what you see in it println()
, it looks like you didn't get UIImage, but some data type instead. It makes sense; you are not going to receive ObjC objects over the network. This way you end up with a file, but when you use the conditional downcast (x as? UIImage
), it returns nil because you don't have a UIImage.
Instead, you will need to drop the PFFile and then perhaps create the UIImage with UIImage(data: file.getData)
or something similar. I don't know exactly how Parse works.
Edit: Here is a related question that you might find helpful: I cannot get the image from PFFile
source to share