Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get current keywindow equivalent for multi window SceneDelegate Xcode 11?

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.

like image 370
Fabiosoft Avatar asked Jul 12 '19 14:07

Fabiosoft


2 Answers

Swift 5.x / iOS 13.x

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
}
like image 177
Alessandro Ornano Avatar answered Nov 13 '22 14:11

Alessandro Ornano


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.

like image 33
NSProgrammer Avatar answered Nov 13 '22 14:11

NSProgrammer