iosswiftuiviewcontrollerdismissviewcontroller

how can I dismiss first vc that second has presented modally on the first vc


I have a view controller that named "firstVC" and another one that named "secondVC" . the secondVC will present modally on the first vc I want to dismiss firstVC and secondVC when user push the button on the secondVC I call the method here But it does execute But nothing will happen in the secondVC this will happen

firstVC.dismiss(animated: true, completion: nil)

if you suggest me to use delegate please tell me how can I use that completely ? I don't know what should I put in the firstVC or what should I put in the secondVC

one more thing

In some other cases I need to execute json in the firstVC and when json has complete the both view controllers (firstVC and secondVC) be dismiss how can I do that too ?


Solution

  • Here is a solution using delegate:

    protocol DismissDelegate{
        func dismissVC()
    }
    
    class FirstViewController: UIViewController, DismissDelegate{
    
        func showSecondVC(){
            let secondVC = SecondViewController()
            secondVC.delegate = self
        }
    
        func dismissVC(){
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    
    class SecondViewController: UIViewController{
        var delegate: DismissDelegate?
    
        @IBAction func buttonAction(sender: UIButton){
            self.dismiss(animated: true, completion: nil)
            delegate?.dismissVC()
        }
    }