Last active
June 22, 2020 10:45
-
-
Save lalkrishna/35fc0ce4646f5166be16bc96e86a4899 to your computer and use it in GitHub Desktop.
This file contains 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 UIApplication { | |
var topViewController: UIViewController? { | |
if #available(iOS 13.0, *) { | |
if UIApplication.shared.supportsMultipleScenes, let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) { | |
return keyWindow.visibleViewController | |
} else { | |
return UIApplication.shared.keyWindow?.visibleViewController | |
} | |
} else { | |
return UIApplication.shared.keyWindow?.visibleViewController | |
} | |
} | |
} | |
extension UIWindow { | |
var visibleViewController: UIViewController? { | |
guard let root = rootViewController else { return nil } | |
return UIWindow.visibleViewController(from: root) | |
} | |
private class func visibleViewController(from vc: UIViewController) -> UIViewController { | |
switch vc { | |
case let navigationController as UINavigationController: | |
return UIWindow.visibleViewController(from: navigationController.visibleViewController!) | |
case let tabBarController as UITabBarController: | |
return UIWindow.visibleViewController(from: tabBarController.selectedViewController!) | |
default: | |
if let presentedViewController = vc.presentedViewController { | |
return UIWindow.visibleViewController(from: presentedViewController.presentedViewController!) | |
} else { | |
return vc; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment