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 sh
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)
}
For Swift 5:
var keyWindow: UIWindow? {
return UIApplication.shared.connectedScenes.filter({$0.activationState == .foregroundActive}).map({$0 as? UIWindowScene}).compactMap({$0}).first?.windows.filter({$0.isKeyWindow}).first
}
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.
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.
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.
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:
if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {
MBProgressHUD.show(text, view:window)
}
Updated for Swift 3: (Thanks @Trevor)
if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
MBProgressHUD.show(text, view:window)
}