Search code examples
swiftviewdidloadpresentviewcontrollerviewdidappeardismissviewcontroller

Perform function on Dismiss of a View Controller


i am calling a GET(method) API on viewDidAppear function of a view controller. i am presenting a new view controller using navigation controller over my first view controller. on the second view controller i am calling an API of Post Method to add another entry into my previous screen Get method API. But when I dismiss the second View Controller the Get API data remains the same and when i again runs the code the data was updated on the first view controller. Can someone tell me that how to check on first view controller that my second view controller is dismissed so that i can call API there.


Solution

  • I got the solution for this. It didn't work by calling the API on viewDidAppear() or viewWIllAppear() . This will be done by using swift closures.

    Below is the code:

    class FirstViewController: UIViewController {
    
        @IBAction func buttonTapped(_ sender: UIButton) {
              guard let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { return }
              secondController.callbackClosure = { [weak self] in
                  print("call API")
              }
            
              self.navigationController?.pushViewController(secondController, animated: true)
        }
    }
    

    On Second view Controller:

    class SecondViewController: UIViewController {
    
          var callbackClosure: ((Void) -> Void)?
    
          override func viewWillDisappear(_ animated: Bool) {
             callbackClosure?()
          }
     }