Get Application's main window
Solution 1
The UIApplicationDelegate
usually has a reference to the "main window":
[[[UIApplication sharedApplication] delegate] window];
Furthermore, UIApplication
has an array of windows [[UIApplication sharedApplication] windows]
.
See the UIApplication Class Reference.
Solution 2
I'm not 100% sure this works in every case but this should work:
UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];
The windows are ordered back to front so the main window should always be at index 0.
Solution 3
Swift 3.0 version of rmaddy's answer:
let window = UIApplication.shared.windows.first
I also should add that since iOS 8.0 UIAlertController
has replaced UIAlertView
and being a view controller you may no longer face the issue of new windows being created.
Solution 4
UIApplication *application = [UIApplication sharedInstance];
NSarray *appWindows = [NSArray arrayWithArray:application.windows];
UIWindow *mainWindow = [appWindows objectAtIndex:0];
I am not sure but this might help.
Solution 5
In Swift:
UIApplication.sharedApplication().delegate?.window
Jonathan.
I'm a 25 year old Software engineer in London, proudly working on the Elfin Market iOS app. I've made a few tweaks for jailbroken iOS and some other stuff.
Updated on March 25, 2020Comments
-
Jonathan. over 4 years
UIApplication has a method
keyWindow
, however if an alert view is showing then this returns the window of the alert view and not the main window of the application.How can I get the app's main window?
-
Jonathan. almost 11 yearsThis is optional for the delegate isn't it? I'm hoping for a more "concrete" way
-
Basem Saadawy over 10 years[[[UIApplication shareApplication] delegate] window] -- works fine.
-
michaellindahl almost 10 yearsYou should call
[[[UIApplication sharedApplication] windows] firstObject]
to avoid an out of bounds exception if there are no windows (not like there would never be any windows, but it's a good habit to avoid those -
fpg1503 over 7 yearsHe said
UIApplication
notNSApplication
, it's tagged as iOS -
Clifton Labrum over 6 yearsIf I had a dollar for every time this has happened in reverse (people answering Cocoa questions with Cocoa Touch answers), I'd be a wealthy man. :) Cut Ted some slack. :)