Skip to content

Instantly share code, notes, and snippets.

@andreinechaev
Created May 9, 2016 23:04
Show Gist options
  • Save andreinechaev/c6faf0dded9c7a8b7425c1ea2783b44c to your computer and use it in GitHub Desktop.
Save andreinechaev/c6faf0dded9c7a8b7425c1ea2783b44c to your computer and use it in GitHub Desktop.
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController!)
}
if let tab = base as? UITabBarController,
let selected = tab.selectedViewController {
return topViewController(selected)
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
}
// Generic Alert with OK Button
// From Andrei Naechaev
func displayAlert(title: String, message: String, okAction: ((UIAlertAction)->Void)?) {
if let topController = UIApplication.topViewController() {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: okAction)
alertController.addAction(okAction)
topController.presentViewController(alertController, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment