Search code examples
iosswiftuiimagepickercontroller

Crash when pushing to another controller after `didFinishPickingMediaWithInfo`


I'm trying to have the app go to a different view controller after the user chooses a photo from the picker.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {

        let previewController = self.storyboard?.instantiateViewController(withIdentifier: "previewVC") as! PreviewViewController
        previewController.previewImage.image = image
        previewController.navigationItem.setHidesBackButton(true, animated: false)
        self.navigationController?.pushViewController(previewController, animated: true)
    }
}

previewController simply has an image view (@IBOutlet weak var previewImage: UIImageView!) and a button to post the photo, so I'm trying to set that image view to display the picked image.

However, I get a crash "unexpectedly found nil when unwrapping an optional value" on the previewController.previewImage.image = image line. previewImage in the previewController is nil in the debugger, but I'm not sure why - isn't that being set as soon as the user hits "choose" in the picker?

Is there another step involved here?


Solution

  • The primary cause of your issue is that you are trying to access the outlets of the view controller too soon. The view controller's views and outlets are not created and assigned immediately after instantiating the view controller.

    It's also poor design to attempt to directly access the views of a view controller from code outside of that view controller. The proper solution, in this case, is to add a UIImage property that you can set. Then let the view controller update its own image view based on the value of that image property at the proper time (such as in viewDidLoad).