Passing data when dismissing Viewcontroller

95 Views Asked by At

I want to pass data to the root view controller, which is ViewController after the previous one is dismissed, I chose to use delegation to solve this problem in this way: Scheme:

ViewController -> SearchViewController

SearchViewController produces data and dismisses

class ViewController: UIViewController, IsAbleToReceiveData {    
@IBAction func addButton_touchUpInside(_ sender: UIButton) {
        performSegue(withIdentifier: "gotoSearchViewController", sender: nil)
    }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "gotoSearchViewController" {
        let vc2 = SearchViewController()
        vc2.delegate = self
    }
}


func passData(city: cityObject) {
        print(city.cityName)

    }
}

The protocol is declared:

protocol IsAbleToReceiveData: class {
   func passData(city : cityObject)
}

In the SearchViewController I have:

weak var delegate: IsAbleToReceiveData?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let citySelected: cities?
    citySelected = self.citiesQueried[indexPath.row]
    RequestAPI.convertData(city: citySelected!) { (city) in

        self.delegate?.passData(city: city)
    }
    dismiss(animated: true, completion: nil)
}

When I try to print the data in the function in ViewController nothing is printed even though in SearchViewController convertData method is returning a cityObject. How can I pass the data to ViewController after dismissing?

2

There are 2 best solutions below

0
Shehata Gamal On BEST ANSWER

Replace

 let vc2 = SearchViewController()
 vc2.delegate = self

with

 if let vc2 = segue.destination as? SearchViewController {
    vc2.delegate = self
 }
0
Anuranjan Bose On

Try

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if let searchVC = segue.destination as? SearchViewController {
      searchVC.delegate = self
}