2
votes

For my second item of my tab bar controller, I have a navigation controller that I want to present modally. I keep getting an error that says

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller .'

Then my app crashes and goes to the app delegate.

This is the code I have so far

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if let restoreID = viewController.restorationIdentifier {
        if restoreID == "NavigationCamera" {
            if let nav = tabBarController.viewControllers![tabBarController.selectedIndex] as? UINavigationController {
                print("Nav is allowed")
                //let newVC = tabBarController.storyboard?.instantiateViewController(withIdentifier: "CameraView")

                tabBarController.present(nav, animated: true, completion: {
                    print("complete")
                })
                return false
            }
        }
    }
    return true
}

This is how my navigation controller is connected to my Tab Bar Controller

2

2 Answers

5
votes

You are trying to present viewcontroller which is already active in UITabBarController, that's why app crashed. Try using this

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if let restoreID = viewController.restorationIdentifier {
        if restoreID == "NavigationCamera" {
                print("Nav is allowed")
                let newVC = tabBarController.storyboard?.instantiateViewController(withIdentifier: "CameraView") as! UIViewController
                tabBarController.present(UINavigationController.init(rootViewController: newVC), animated: true, completion: {
                    print("complete")
                })
                return false
        }
    }
    return true
}
0
votes

You need to try and change the selectedViewController property within the tabBarController rather then using the present method. Try this instead

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if let restoreID = viewController.restorationIdentifier {
        if let restoreID == "NavigationCamera" {
            print("Nav is allowed")
            tabBarController.selectedViewController = tabBarController.viewControllers![tabBarController.selectedIndex] as? UINavigationController
            return false
        }
    }
    return true
}