How to get Deprecated keyWindow in Swift

by

Note: Discussion in this post assumes we are considering single window based scenario.

Sometimes I need to access the main window of my app to add some temporary views to it - making it appear forefront no matter at what depth of user’s navigation-flow I am in.

From old days of single window based app we have been using very convenient property handed to us: keyWindow

keyWindow
This property holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible() message.


guard let window = UIApplication.shared.keyWindow else {return}

It has been long time. Now this has been deprecated from iOS 13 onwards.

We have our windows accessible from windows array:


let window = UIApplication.shared.windows[0]

A free assumption would be that first window in array would be the main window of the app - being the root. We want the root window so that any view being added be directly on top for our given purpose here. It worked good until unexpected happened. First object did not give UIWindow but UITextEffectsWindow. I could not add my view on the top anymore - adding to UITextEffectsWindow didn’t work for curiosity.

I stumbled about this when I inspected the reference in breakpoint:


po UIApplication.shared.windows

▿ 2 elements - 0 : <UITextEffectsWindow: 0x10185f600; frame = (0 0; 375 667); opaque = NO; autoresize = W+H; layer = <UIWindowLayer: 0x28110ece0>> - 1 : <UIWindow: 0x10120f330; frame = (0 0; 375 667); autoresize = W+H; gestureRecognizers = <NSArray: 0x281f7af10>; layer = <UIWindowLayer: 0x28112a020>>

I checked on web about UITextEffectsWindow for information. I found it is the root window when keypad is visible in our screen. I cross referenced with my pattern and it was correct. In this given example, my UIViewController always keeps keypad visible. For certain input response I was trying to show some custom made notification on top of the UIWindow. I already learnt that for keypad situation UIWindow is not the first object in the array.

I found many useful solutions on the web. Few of them is:


UIApplication.shared.windows.filter {$0.isKeyWindow}.first


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

You might also like: UIImagepicker controller allowsEditing not working

More Articles

Recommended posts