Ian Bell Ian Bell - 1 year ago 80
iOS Question

Call method of presenting viewcontroller from modal

I have a

: if a user is not logged in, I open modally a new controller, so that the user can login. The opening is done this way:

self.performSegue(withIdentifier:"loginView", sender:self)

After login, I want to dismiss this modal and come back to my viewcontroller: this is very easy to do, but I want another thing. I want the presenting view controller call this method before I dismiss my modal:

func goToContent(animated:Bool){
let viewController:ContentViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Content") as! ContentViewController
self.navigationController!.pushViewController(viewController, animated: animated)

Is this possible? From my modal I could not get a reference to the presenting viewController. That is: I tried the following, but I don't know if this is the right way to proceed:

let vc:ViewController = ViewController()

This works but aren't there better solutions?

[Edit to reply to a question in the comments]
I implemented a delegate this way:

in the ViewController:

class ViewController: UIViewController, LoginViewControllerDelegate {

var loginViewController:LoginViewController = LoginViewController()

override func viewDidLoad() {
loginViewController.delegate = self

In LoginViewController file, just before the class declaration:

protocol LoginViewControllerDelegate: class {

func goToContent(animated:Bool)


Inside LoginViewController:

weak var delegate: LoginViewControllerDelegate?

in its view did load (just for testing: I simply put a print inside the body of goToContent):


Answer Source

You need to create a delegate of ContentViewController and in that delegate you need to add this method goToContent.

Now when you are logged in successfully, you need to call this delegate method. It will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download