1

I want to go back to mainviewcontroller when I hit logout button, but it gives me:

fatal error: unexpectedly found nil while unwrapping an Optional value

navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logOut))


 func logOut(){

    let mainViewController = MainViewController()
    present(mainViewController, animated: true, completion: nil)
}
Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75
Vika
  • 19
  • 6
  • is this controller embed in navigation controller? – lithium Dec 02 '16 at 07:35
  • if not, have you tried just dismiss current controller (it seems that you don't want to create new instance of mainViewController, you want to go back to this controller). – lithium Dec 02 '16 at 07:36
  • Yes. MainViewController is first after navigationController – Vika Dec 02 '16 at 07:38
  • Already tried to dismiss, didn't work – Vika Dec 02 '16 at 07:38
  • if you have it embed in navigation controller (both of them: main and current one), you have to use self.navigationController.popViewController or popToRootViewController. popViewController will bring you back to the previous controller, and popToRoot — to the first (root) controller in navigation. – lithium Dec 02 '16 at 07:41
  • It works, but it writes that "expression of type UIViewController is unused" – Vika Dec 02 '16 at 07:47
  • oh, yeah. in swift 3 it is advised to use "_ = self.navigationController.popViewController" instead of "self.navigationController.popViewController". (or, maybe, "let _ = ...", try this if the first option won't work) – lithium Dec 02 '16 at 07:59
  • First one worked, thank you! – Vika Dec 02 '16 at 08:02

0 Answers0