0

When i do "image = self.originalImageView.image!" in the following code. I'm getting a error signal " fatal error: unexpectedly found nil while unwrapping an Optional value". Can anyone please tell me how i can overcome this ?

func displayPhoto()
    {
        let imageManager = PHImageManager.defaultManager()

       //  var image:UIImage = self.imageView.image!
    var ID = imageManager.requestImageForAsset(self.photosAsset[self.index] as! PHAsset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFit, options: nil, resultHandler: {(result:UIImage!, info: [NSObject: AnyObject]!)in
        self.originalImageView.image = result     
    })

    var image:UIImage?
    image = self.originalImageView.image!
    print("Hello")

   self.imageView.image = image!.getGrayScale()

}
  • look into your closure. put a breakpoint to self.originalImageView.image = result and check if result is nil. – Fabio Mignogna Oct 21 '15 at 15:54
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – MKII May 16 '16 at 09:08

1 Answers1

1

requestImageForAsset works asynchronously, the result is returned later in the block after the method exited, put the code to process the result into the block.

And probably you have to dispatch updating the UI on the main thread.

func displayPhoto()
{
    let imageManager = PHImageManager.defaultManager()

    //  var image:UIImage = self.imageView.image!
    var ID = imageManager.requestImageForAsset(self.photosAsset[self.index] as! PHAsset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFit, options: nil, resultHandler: {(result:UIImage!, info: [NSObject: AnyObject]!)in
    dispatch_async(dispatch_get_main_queue()) {
      self.originalImageView.image = result
      self.imageView.image = result.getGrayScale()
    }  
    print("Hello")   
  })
}
vadian
  • 274,689
  • 30
  • 353
  • 361