I'm currently writing a social networking application in Swift. Inside my app I have feature that a user can send a message to the timeline with a image attached. I want to be able to retrieve the image and preview it using a UIImageView inside my timeline. I wrote the following function but I'm receiving a "unexpected found nil while unwrapping a Optional Value" error. I'm hoping somebody in the community can point out what I'm doing wrong.
func loadImages()
{
var query = PFQuery(className: "imagesUploaded")
query.orderByDescending("objectID")
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!,error:NSError!) -> Void in
if error == nil {
let imagesobjects = objects as [PFObject]
for object : PFObject in objects as [PFObject] {
let image = object["filename"] as PFFile
image.getDataInBackgroundWithBlock {
(imageData:NSData!, error:NSError!) -> Void in
if error == nil {
let finalimage = UIImage(data: imageData)
self.timelineImages.append(finalimage!)
self.timelineimage.image = finalimage?
}
}
}
}
}
}
Given that the error is happening around these lines:
self.timelineImages.append(finalimage!)
self.timelineimage.image = finalimage?
I would suggest it is either finalimage
, timelineImages
or timelineimage
.
For finalimage I would use if let
:
if let finalimage = UIImage(data: imageData) {
self.timelineImages.append(finalimage)
self.timelineimage.image = finalimage
}
This safely runs the code only if finalimage got a value.
If one of the others is coming back as nil you can solve that with ?
. thus your final code looks like this:
if let finalimage = UIImage(data: imageData) {
self.timelineImages?.append(finalimage)
self.timelineimage?.image = finalimage
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.