Skip to content

Instantly share code, notes, and snippets.

@matteodanelli
Created February 27, 2018 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteodanelli/b8dcdfef39e3417ec7116a2830ff67cf to your computer and use it in GitHub Desktop.
Save matteodanelli/b8dcdfef39e3417ec7116a2830ff67cf to your computer and use it in GitHub Desktop.
Get visible view controller
extension UIWindow {
func visibleViewController() -> UIViewController? {
if let rootViewController: UIViewController = self.rootViewController {
return UIWindow.getVisibleViewControllerFrom(vc: rootViewController)
}
return nil
}
class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {
switch(vc){
case is UINavigationController:
let navigationController = vc as! UINavigationController
return UIWindow.getVisibleViewControllerFrom( vc: navigationController.visibleViewController!)
break;
case is UITabBarController:
let tabBarController = vc as! UITabBarController
return UIWindow.getVisibleViewControllerFrom(vc: tabBarController.selectedViewController!)
break;
default:
if let presentedViewController = vc.presentedViewController {
//print(presentedViewController)
if let presentedViewController2 = presentedViewController.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(vc: presentedViewController2)
}
else{
return vc;
}
}
else{
return vc;
}
break;
}
}
}
// HOW TO USE
if let topController = UIApplication.shared.delegate?.window??.visibleViewController() {
topController.doSomething()
}
@YogeshPateliOS
Copy link

Working great. You can remove break it works. Thanks!

@Fostahh
Copy link

Fostahh commented Mar 31, 2023

Still working! Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment