45

I have only one window and I tried

UIWindow* mWindow = [[UIApplication sharedApplication] keyWindow];

but this returned nil.

I also tried:

UIWindow* mWindow = (UIWindow*)[[UIApplication sharedApplication].windows objectAtIndex:0];

But this raised an exception and the app closed, when I tried to print out

[[UIApplication sharedApplication].windows count]

It printed 0

Note: I am putting this in my only view controller's viewDidLoad method and this is completely a new iPad View Based Application so I changed nothing, just trying to get the window

Please help me to get this object

6 Answers6

49

If your main window is an outlet of your AppDelegate (which should be the case), you may simply use

MyAppDelegate* myDelegate = (((MyAppDelegate*) [UIApplication sharedApplication].delegate));
[myDelegate.window ...]
Philipp Schlösser
  • 5,179
  • 2
  • 38
  • 52
42

Easiest way is to get the window from the app delegate instead:

UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
// Do something with the window now
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
20

Your application's key window isn't set until [window makeKeyAndVisible] gets called in your app delegate. Your UIViewController is probably being loaded from a NIB before this call. This explains why keyWindow is returning nil.

Luckily, your view controller doesn't need to go through UIApplication to get the window. You can just do:

UIWindow *mWindow = self.view.window;
cduhn
  • 17,818
  • 4
  • 49
  • 65
7
[[[UIApplication sharedApplication] windows] objectAtIndex:0]; // You can also check the count of this to make sure, because if there are no windows it will crash.
BadPirate
  • 25,802
  • 10
  • 92
  • 123
0

With iOS 13+ you should use:

if let currentScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
    let window = currentScene.keyWindow {
    // now window contains the active window
}
0

You can achieve this in multiple ways. I like to use one of the following.

Use this when you need to access it just once.

if let window = UIApplication.shared.windows.first as UIWindow? {
    // Action
}

If you need to access the UIWindow multiple times, I would suggest extending a class. I like to extend the UIViewController.

extension UIViewController {
    /// Returns the UIWindow if available.
    public var window: UIWindow? {
        UIApplication.shared.windows.first as UIWindow?
    }
}
Sem
  • 21
  • 5