Nick
Nick

Reputation: 1444

Pass Captured/Gallery Image from one ViewController to another

I want to capture a photo or pick it from the gallery and then pass it inside an imageView to another ViewController. I make the sequel successfully but I don't know how to pass the image from the imagePickerController.

First ViewController

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let selectedImage = info[.originalImage] as? UIImage{
            imagePicker.dismiss(animated: true){
                self.performSegue(withIdentifier: "goToCropScreen", sender: self)
            }

        }

    }

    //Navigation to other screens
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToCropScreen"{
            let destinationVC = segue.destination as! CropViewController
            destinationVC.imageToCrop = //Here is the problem. Idont know what image to use.
        }
    }

Second ViewController

class CropViewController: UIViewController {

    @IBOutlet weak var cropImageView: UIImageView!

    var imageToCrop : UIImage?

    override func viewDidLoad() {
        super.viewDidLoad()

        cropImageView.image = imageToCrop

    }


}

I know that I can't use selectedImage because its inside the imagePickerController. Is there a way to use it like globally.

Upvotes: 0

Views: 39

Answers (1)

RajeshKumar R
RajeshKumar R

Reputation: 15758

Create a variable in FirstViewController. And store the selected image in this variable and pass the value in prepare for segue method

class FirstViewController: UIViewController {

    var selectedImage: UIImage?

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

            if let selectedImage = info[.originalImage] as? UIImage{
                imagePicker.dismiss(animated: true){
                    self.selectedImage = selectedImage
                    self.performSegue(withIdentifier: "goToCropScreen", sender: self)
                }

            }

        }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToCropScreen"{
            let destinationVC = segue.destination as! CropViewController
            destinationVC.imageToCrop = self.selectedImage
        }
    }
}

Upvotes: 1

Related Questions