Skip to content

Instantly share code, notes, and snippets.

@lalkrishna
Last active June 22, 2020 10:45
Show Gist options
  • Save lalkrishna/35fc0ce4646f5166be16bc96e86a4899 to your computer and use it in GitHub Desktop.
Save lalkrishna/35fc0ce4646f5166be16bc96e86a4899 to your computer and use it in GitHub Desktop.
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