Created
February 27, 2018 10:03
-
-
Save matteodanelli/b8dcdfef39e3417ec7116a2830ff67cf to your computer and use it in GitHub Desktop.
Get visible view controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Still working! Thank you so much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working great. You can remove break it works. Thanks!