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

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


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 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)}


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.


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 })