Skip to content

Instantly share code, notes, and snippets.

@originell
Created January 7, 2015 23:31
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 originell/a42b2b83c2ca1865ed20 to your computer and use it in GitHub Desktop.
Save originell/a42b2b83c2ca1865ed20 to your computer and use it in GitHub Desktop.
Reliably get the top most UIViewController. Tested with iOS7 and 8
// Note: There are no fancy error checks in here. This is just meant to quickly demonstrate this.
// I was extremely frustrated because most posts on stackoverflow are missing the important point
// of checking for the "presentedViewController".
// If you are working in a view that is *already living* in the view hierarchy.
var topMostController = view.window!.rootViewController!
// or
// If you don't have a view in the hierarchy yet (as it might happen in viewDidLoad etc.)
// (there is also the possibility to use UIApplication.sharedApplication().keyWindow, though it seems
// that the internet's general opinion is that it's safer to use the delegate's window)
var topMostController = UIApplication().sharedApplication().delegate!.window!!.rootViewController
// Important: do not forgot to check for this. Presented ViewControllers are in front of others!
// TODO: Might be necessary to do this recursively?
if let presentedVC = topMostController.presentedViewController {
topMostController = presentedVC
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment