Vaibhav Arora Vaibhav Arora - 1 month ago 10
Swift Question

UIImage not passing from one ViewController to other

I am trying to pass the image which is captured from

UIImagePickerController
to another
ViewController
but the image is not getting passed.

This is the code of the first
ViewController
:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
newImageView.contentMode = .scaleAspectFit
newImageView.image = chosenImage

self.performSegue(withIdentifier: "pass", sender: self)

dismiss(animated:true, completion: nil)

let svc = self.storyboard!.instantiateViewController(withIdentifier: "demoViewController") as! demoViewController
present(svc, animated: true, completion: nil)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pass"
{
let imgpass = segue.destination as! demoViewController
imgpass.newphoto = chosenImage
}
}


Code for the second
ViewController
:

override func viewDidLoad() {
super.viewDidLoad()

myImageView.image = newphoto
}


I went through a lot of other similar postings and implemented them too but couldn't get the image passed.

Answer

Try this

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
        if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

        newImageView.contentMode = .scaleAspectFit
        newImageView.image = chosenImage

        picker.dismiss(animated: true, completion: nil)

        let svc = self.storyboard!.instantiateViewController(withIdentifier: "demoViewController") as! demoViewController
        svc.newphoto = chosenImage
        self.present(svc, animated: true, completion: nil)
    }
}