Search code examples
iosswiftxcodeimage-processinguiimageview

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value. Getting image from Gallery swift


I am trying to get an image from the gallery through a button but I am getting this error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

I have looked at all the other questions that are similar to mine, but for some reason, I am not able to solve my problem.

class ViewController: UIViewController, VNDocumentCameraViewControllerDelegate,  UINavigationControllerDelegate, UIImagePickerControllerDelegate  {

    var textRecognitionRequest = VNRecognizeTextRequest()
    var recognizedText = ""
    var text2 = "";

    @IBOutlet weak var imageTest: UIImageView!
    @IBOutlet weak var centreView: CardView!
    @IBOutlet weak var centreViewBorder: UIView!
    @IBOutlet weak var circleButton: UIButton!



    override func viewDidLoad() {
        super.viewDidLoad()
        imageTest = UIImageView()
```

```
IBAction func uploadImage(_ sender: UIButton) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        self.present(imagePicker, animated: true, completion: nil)

    }
   func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[.originalImage] as? UIImage else {
            fatalError("Error")
        }
        imageTest!.image = image
    dismiss(animated: true, completion: nil)

    }
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}



Solution

  • The first issue is you are switching your imageTest variable to a different instance of UIImageView. Remember, when you declare an IBOutlet and use a ! your variable's memory pointer references a nil value in memory. You no longer need to assign it again. Additionally, when referenced in the future it will no longer need to be unwrapped because the ! in the declaration makes the force unwrap explicit.

    override func viewDidLoad() {
            super.viewDidLoad()
            imageTest = UIImageView()  -- ***** Remove this line *****
    

    Also, this needs to be changed

       func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            guard let image = info[.originalImage] as? UIImage else {
                fatalError("Error")
            }
            imageTest!.image = image -- ******* REMOVE THE BANG HERE ******
        dismiss(animated: true, completion: nil)
    
        }