zumzum
zumzum

Reputation: 20138

How do I get the keyWindow reference in a swift app?

In Objective-C in the viewDidLoad method of a UIViewController I do this to get the keyWindow reference in my iOS app:

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

So, I am porting this view controller into Swift and I do this one the viewDidLoad call:

let window = UIApplication.sharedApplication().keyWindow

I am trying to understand why the window is nil. When I put a breakpoint right after that line I then inspect window in the console and I get this:

(lldb) po window
nil

How can I get window to be a valid reference to the keyWindow of my application in swift?

Upvotes: 35

Views: 63443

Answers (7)

superarts.org
superarts.org

Reputation: 7238

I came to this question when I was searching for getting window in swift. If you want to get window instead of keyWindow, try this (Swift 2):

if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate, let window = delegate.window {
    MBProgressHUD.show(text, view:window)
}

Updated for Swift 3: (Thanks @Trevor)

if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window {
    MBProgressHUD.show(text, view:window)
}

Upvotes: 42

nomnom
nomnom

Reputation: 994

Swift 5.1

Works for me

If you are also looking for a way to deal with foreground and background modes you should try this

UIApplication.shared.windows.first(where: { $0.isKeyWindow })

Upvotes: 20

Iliyan Kafedzhiev
Iliyan Kafedzhiev

Reputation: 397

The easiest way to do that is:

in Objective-C

[UIApplication sharedApplication].windows.firstObject

in Swift

UIApplication.shared.windows.first!

Note that this works only if you do not support multiple windows.

Upvotes: 4

juhan_h
juhan_h

Reputation: 4011

Swift 4 simply has UIApplication.shared.keyWindow property, no casting necessary.

Note that iOS 13/iPadOS introduces UIScenes and explicit support for multiple windows, and thus deprecates the concept of keyWindow as it is no longer valid.

This question has an overview how to get access to scene based windows.

Upvotes: 28

Irshad Ahmad
Irshad Ahmad

Reputation: 1383

Don't call window in didLoad function call the keyWindow in viewDidAppear function of ViewController

Upvotes: 2

rmooney
rmooney

Reputation: 6229

Updating superarts.org's answer for Swift 3:

if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window { 
      MBProgressHUD.show(text, view: window)
}

Upvotes: 4

rdelmar
rdelmar

Reputation: 104082

The key window must not yet be set at the time of viewDidLoad. Your code works fine in viewDidAppear. Alternately, you can get the windows array in viewDidLoad, and get one (if there's more than one) of the windows from that array.

Upvotes: 3

Related Questions