简体   繁体   中英

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


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)

    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM