Get Application's main window

40,998

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
Share:
40,998
Jonathan.
Author by

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, 2020

Comments

  • Jonathan.
    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.
    Jonathan. almost 11 years
    This is optional for the delegate isn't it? I'm hoping for a more "concrete" way
  • Basem Saadawy
    Basem Saadawy over 10 years
    [[[UIApplication shareApplication] delegate] window] -- works fine.
  • michaellindahl
    michaellindahl almost 10 years
    You 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
    fpg1503 over 7 years
    He said UIApplication not NSApplication, it's tagged as iOS
  • Clifton Labrum
    Clifton Labrum over 6 years
    If 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. :)