Search code examples
swiftuiimageview

Choosing An Image From Gallery And Display Into ImageView into Different VC - Swift


Not too sure why but I have run into an issue. Essentially, I have a button in one VC which opens an action sheet. Once a user chooses a picture from their library or takes a photo and chooses that, I wanted to navigate away from that VC, onto a new VC to display that picture chosen. However, I run into this issue at the bottom. It works when everything is in one VC, but I am assuming I am not passing the image correctly. Can anyone have a look, and suggest ways to make this work? Thanks!

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

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let moreDetail = storyboard.instantiateViewController(identifier: "AddPostViewController") as! AddPostViewController
    picker.dismiss(animated: true, completion: nil)
    guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {return}
    moreDetail.postImage.image = selectedImage // error
    self.navigationController?.pushViewController(moreDetail, animated: true)
}

Solution

  • Use below code :-

    For First VC:--

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    if let moreDetail = storyboard.instantiateViewController(identifier: "AddPostViewController") as? AddPostViewController {
    
    
      picker.dismiss(animated: true) {
         
        guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] 
     as? UIImage else {return}
      
       moreDetail.img = selectedImage 
            
       self.navigationController?.pushViewController(moreDetail, animated: true)   
      }
              
     } 
    
    }
    
    

    For Second VC :-

    class AddPostViewController: UIViewController {
    
    @IBOutlet weak var postImage: UIImageView!
    var img : UIImage ?
    
      override func viewDidLoad() {
            super.viewDidLoad()
            
         if let img = self.img  {
            self.postImage.image = img
        }
            
    
      }
    
    }