iOS App wide operations Get the top most UIViewController

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A common approach to get the top most UIViewController is to get the RootViewController of your active UIWindow. I wrote an extension for this:

extension UIApplication {

func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController {
    
    if let nav = base as? UINavigationController {
        return topViewController(nav.visibleViewController)
    }
    
    if let tab = base as? UITabBarController {
        if let selected = tab.selectedViewController {
            return topViewController(selected)
        }
    }
    
    if let presented = base?.presentedViewController {
        return topViewController(presented)
    }
    
    return base!
}


Got any iOS Question?