Abhishek Renganathan
Abhishek Renganathan

Reputation: 11

Swift error fatal error: unexpectedly found nil while unwrapping an Optional value

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

}

Upvotes: 0

Views: 588

Answers (1)

vadian
vadian

Reputation: 285240

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

Upvotes: 1

Related Questions