Reading time: 1 min
Here's a quick recipe for getting the key window, top or root View Controller, in a scene-based SwiftUI app.
extension UIApplication {
var currentKeyWindow: UIWindow? {
UIApplication.shared.connectedScenes
.filter { $0.activationState == .foregroundActive }
.map { $0 as? UIWindowScene }
.compactMap { $0 }
.first?.windows
.filter { $0.isKeyWindow }
.first
}
var rootViewController: UIViewController? {
currentKeyWindow?.rootViewController
}
var visibleViewController: UIViewController? {
currentKeyWindow?.visibleViewController
}
}