Ian Bell Ian Bell - 23 days ago 8
iOS Question

Call method of presenting viewcontroller from modal

I have a

ViewController
: 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:

if(!loggedIn){
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()
vc.goToContent(animated:false)


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() {
super.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):

delegate?.goToContent()

Answer

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.

Comments