iosswiftuiviewcontrollercallbackpopviewcontroller

How to receive same callback in two ViewControllers when one is opened?


I want to receive the same callback in the ViewController that is opened at in the time that server response in my Swift Application.

I have two ViewControllers. The first ViewController registers a callBack from a class "NetworkService".

The second ViewController is Opened from the first ViewController and the second receives the "NetworkService" from the firstViewController initialized in a variable, and then registers the same callBack.

When I try to receive the callback from the server, if the first ViewController is opened I get the response. If I open the second ViewController and I resend the response I get this correctly in the second ViewController.

BUT if I return to the first ViewController and I get the response, its' only received on the Second ViewController all times.

class NetworkService {

    var onFunction: ((_ result: String)->())?

    func doCall() {
        self.onFunction?("result")
    }

}


class MyViewController: UIViewController {

    let networkService = NetworkService()

    override func viewDidLoad() {
        super.viewDidLoad()

        networkService.onFunction = { result in
            print("I got \(result) from the server!")
        }

    }
}

I open the secondViewController like:

let vc = self.storyboard!.instantiateViewController(withIdentifier: "second") as! SecondViewController
vc. networkService = networkService
        self.navigationController?.pushViewController(vc, animated: true)

And the Second ViewController:

class SecondViewController: UIViewController {

    var networkService: NetworkService?

    override func viewDidLoad() {
        super.viewDidLoad()

        networkService!.onFunction = { result in
            print("I got \(result) from the server!")
        }

    }
}

How would it be possible to receive the response in the first ViewController again, then return to first ViewController from the second calling the popViewController?

self.navigationController?.popViewController(animated: false)  

Solution

  • How about calling the function within viewDidAppear on both ViewControllers so that you get your response every time you switch between the two views? You wouldn't need to pass networkService between the ViewControllers.

    override func viewDidAppear(_ animated: Bool) {
    
      networkService!.onFunction = { result in
                print("I got \(result) from the server!")
            }
    
    }