Search code examples
iosswiftuiviewcontrollerviewcontrollertvos

Swift: Unable to communicate data between view controllers when using present


I have implemented these programmatically.

TableViewCell:

class TableViewCell: UITableViewCell{

    var moviesItems: [Document] = []

    @objc func didPressVoirToutButton() {
        print("Voir tout button was pressed.")
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
           let vc: VoirToutViewController = storyboard.instantiateViewController(withIdentifier: "VoirToutViewController") as! VoirToutViewController
           self.viewController?.present(vc, animated: false, completion: nil)
           print("moviesItemsArray being communicated to moviesItems",moviesItems) 
           // moviesItems is not empty
            vc.voirToutMoviesItemsArray=self.moviesItems
    }
}

VoirToutViewController:

class VoirToutViewController: UIViewController {
    var voirToutMoviesItemsArray : [Document]?
}

I am trying to communicate moviesItems from TableViewController to VoirToutViewController by setting it to voirToutMoviesItemsArray.

The problem is VoirToutViewController.voirToutMoviesItemsArray always remains empty.
Any idea what I'm doing wrong?


Solution

  • It is nil because you are presenting the vc before you initialize its value. To fix:

    Place this line

    vc.voirToutMoviesItemsArray=self.moviesItems

    before this one

    self.viewController?.present(vc, animated: false, completion: nil)