Skip to content

Instantly share code, notes, and snippets.

@savasadar
Created April 16, 2019 12:36
Show Gist options
  • Save savasadar/fd5354080c49138e6bba5e14dd0cdddd to your computer and use it in GitHub Desktop.
Save savasadar/fd5354080c49138e6bba5e14dd0cdddd to your computer and use it in GitHub Desktop.
Get the topmost viewController anywhere in the app (typically from the appDelegate). Get the current visible viewController.
extension UIViewController {
func topMostViewController() -> UIViewController {
if let presented = self.presentedViewController {
return presented.topMostViewController()
}
if let navigation = self as? UINavigationController {
return navigation.visibleViewController?.topMostViewController() ?? navigation
}
if let tab = self as? UITabBarController {
return tab.selectedViewController?.topMostViewController() ?? tab
}
return self
}
}
extension UIApplication {
func topMostViewController() -> UIViewController? {
return self.keyWindow?.rootViewController?.topMostViewController()
}
}
//Use Like This
//let topMostViewController = UIApplication.shared.topMostViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment