Diz
Diz

Reputation: 89

iOS 13 isKeyWindow always returns nil

I am wondering why:

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

always returns nil both in the simulator and on device. You can confirm this by putting a break point in viewDidLoad in any view controller and printing the object to the console.

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

The only way I can get the "keyWindow" is by getting

UIApplication.shared.windows.first

But there is no explicit mention that it is key. What if there are multiple instances of my app on iPad Split view?

Any ideas?

My thinking is, if there is only one window it's key by default and if you're running more than one window on iPad the one that is currently being interacted with will become the key window, however, I haven't tested this.

Upvotes: 5

Views: 695

Answers (3)

Jafar Khoshtabiat
Jafar Khoshtabiat

Reputation: 703

func getActiveScene() -> UIScene {
    let scenes = UIApplication.shared.connectedScenes
    guard !scenes.isEmpty else { fatalError("No connected scene can be found") }
    if let currentScene = scenes.first(where: { $0.activationState == .foregroundActive }) {
        return currentScene
    }
    if let currentScene = scenes.first(where: { $0.activationState == .foregroundInactive }) {
        return currentScene
    }
    guard let firstScene = scenes.first else { fatalError("Not possible") }
    return firstScene
}

you can cast result to UIWindowScene like this:

let currentScene = getActiveScene()
guard let currentWindow = currentScene as? UIWindowScene else { fatalError() }

Upvotes: 1

Diz
Diz

Reputation: 89

Just answering this in 2024 for anyone that lands on it, just write an extension on UIWindow.

import UIKit

extension UIWindow {
    static var key: UIWindow? {
        return UIApplication.shared.connectedScenes
            .flatMap { ($0 as? UIWindowScene)?.windows ?? [] }
            .first { $0.isKeyWindow }
    }
}

You can use it in your apps like this:

if let keyWindow = UIWindow.key {
    // Use keyWindow here
}

Hope this helps!

Upvotes: -1

Boris
Boris

Reputation: 402

Have you tried this?

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

Upvotes: -2

Related Questions