Search code examples
iosswiftuiviewcontrolleruinavigationcontroller

how to prevent user from being able to call the same view controller twice in a row from a slide out settings menu?


I have the following function that identifies the navigation controller that is embedded in a tab bar controller and pushes a profile view controller. This function works, but I want to do some check that prevents it from presenting the profile view controller a second time if this function is called from the slide out menu while the profile view controller is the most recently pushed view controller. Here's the function:

private func toProfile() {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
        let tbc = appDelegate.window?.rootViewController as? TabBarController,
        let nav =  tbc.viewControllers?[tbc.selectedIndex] as? UINavigationController else { return }
    let profileVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "profileVC")
    nav.pushViewController(profileVC, animated: true)
    delegate?.dismissSettingsVC()
}

I tried:

if nav.viewControllers.last == profileVC {
    print("Do nothing")
} else {
    nav.pushViewController(profileVC, animated: true)
}

but it never says the two are equal. How do I make an if statement to check if the last view controller pushed is profileVC?


Solution

  • You need to check the type

    if nav.viewControllers.last is ProfileVC {
       print("Do nothing") 
    }
    else { 
      nav.pushViewController(profileVC, animated: true) 
    }
    

    Currently you compare 2 instances of the same type and for sure they are not equal