Get the top most UIViewController

suggest change

A common approach to get the topmost UIViewController is to start at the root view controller of the active UIWindow. keyWindow is nil for a scene-based app, and return base! crashes when base is nil. The extension was missing its closing brace.

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!
}
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents