1
votes

I have read some answers like dismissing the current ViewController but my situation is different because I am presenting another ViewController.

This code presents the view controller with its navigation controller although I cannot access it's properties:

@IBAction func didTouchAddFriend(_ sender: UIButton) {
DispatchQueue.main.async {

    let storyBoard = UIStoryboard(name: "CustomContact", bundle: nil)
        let customContactVC = storyBoard.instantiateViewController(withIdentifier: "CustomContact")

}
}

While this one doesn't work

@IBAction func didTouchAddFriend(_ sender: UIButton) {
    DispatchQueue.main.async {

        let navigation = UIStoryboard.init(name: "CustomContact", bundle: nil).instantiateInitialViewController() as! UINavigationController
        let pickerUserVC = navigation.viewControllers.first as! CustomContactsViewController
        self.present(pickerUserVC, animated: true, completion: nil)

    }
}

I have another story board named CustomContact.storyboard which containts a CustomContactsViewController

When I click the didTouchAddFriend, it just shows me this error:

'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller <Main.MainViewController: 0x7ff29f06ac00>.'

I cannot understand the error cos when I printed the value of pickerUserVC, it show the right view controller:

<Main.CustomContactsViewController: 0x7fd1b7922400>

MainViewController is the current view controller implementing the didTouchAddFriend function

1

1 Answers

9
votes

You ought to present the navigation controller (which hosts the CustomContactsViewController as it's root view controller).

Moreover, you can skip the Dispatch call, since we are in an @IBAction which already runs in the main thread:

@IBAction func didTouchAddFriend(_ sender: UIButton) {
    let navigation = UIStoryboard.init(name: "CustomContact", bundle: nil).instantiateInitialViewController() as! UINavigationController
    let pickerUserVC = navigation.viewControllers.first as! CustomContactsViewController
    self.present(navigation, animated: true, completion: nil)
}