I'm converting my iOS13 app for iPadOS to SceneDelegate (multi window).
How can I get the current UIWindow from the current SceneDelegate?
I know that a can access the current scene using UIView.window
or UIViewController.view.window
, but I have a non UI class (AppDelegate) where I need to get the window (keyWindow until iOS12) to show a snack bar on top of everything.
I used to do [UIApplication sharedApplication].keyWindow
but now, of course, that's wrong.
Inspired by many solutions, to get back my old window property (searching it inside the connectedScenes) I've realized a little extension:
extension UIApplication {
var currentWindow: UIWindow? {
connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
}
}
Usage:
if let window = UIApplication.shared.currentWindow {
// do whatever you want with window
}
You'll want to simply iterate through all your windows and find the key window manually.
for (UIWindow *window in [UIApplication sharedApplication].windows) {
if (window.isKeyWindow) {
// you have the key window
break;
}
}
DO NOT use UISceneActivationStateForegroundActive
as the check. That means something different and folks are introducing bugs by using logic to find the first UISceneActivationStateForegroundActive
window scene.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With