简体   繁体   中英

How to call a function when a Modal View Controller has been dismissed

I currently have a modal view controller that I am using to sign in. Once the sign in is completed the modal dismisses. I am having trouble getting a func to run on the original view controller once the modal is dismissed.

I call the modal through a segue that is connected to a button on the main view controller. The func I want to run is already in viewDidLoad and viewWillAppear where it works when the view controller is originally loaded and appears.

I am trying to figure out how to get it to run the func again once returned to the view dater the modal is dismissed.

Original View Controller:

class SignInView: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.hidesBackButton = true

}

override func viewWillAppear(_ animated: Bool) {

    checkUser()

}

Modal View Controller:

@IBAction func submitBtn(_ sender: Any) {

    if username.text == "" && password.text == "" {
        displayAlert("Error", message: "Please Enter an Username and Password")
    }

    if username.text == "" {
        displayAlert("Error", message: "Please Enter an Username")
    }

    if password.text == "" {
        displayAlert("Error", message: "Please Enter a Password")
    }

    self.emailLogin()

}

func emailLogin() {

    guard let username = username.text, let password = password.text else {
        return
    }

    Auth.auth().signIn(withEmail: username, password: password) { (user, error) in

        if error != nil {
            print("Login Error")
            self.displayAlert("Failed to Login", message: "Username or Password is Inccrrect")
            return
        } else {

        print("Successfully Signed In")

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

        }

    }

}

One possibility: Change

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

To

self.dismiss(animated: true) {
    theSignInView.callTheMethod()
}

The protocol/delegate pattern is often used to facilitate this approach.

viewDidLoad is called once when the vc is first initated , viewWillappear,viewDidAppear are called when you dismiss a model say with overCurrentContext / pop from navigationController

If the above isn't your case then you need a delegate inside prepareForSegue

let des = segue.destination as! ModalVC
des.delegate = self

class ModelVC://
  weak var delegate:MainVC?
}

Then before the dismiss use

delegate?.checkUser()
self.dismiss(animated: true, completion: nil)

Also when you use viewWillAppear don't forget super.viewWillAppear(animated)

override func viewWillAppear(_ animated: Bool) {
   super.viewWillAppear(animated)
   checkUser() 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM