— iOS, Swift, iOS 13, UIWindow — 1 min read
With the release of iOS 13, Apple deprecated the keyWindow
property, which was a common way to access the main window of an app. This change was made to support new features like multiple scenes in iPadOS. This article guides you through adapting your iOS applications to handle this deprecation.
The deprecation of keyWindow
in iOS 13.0 is primarily due to the introduction of multi-window support in iPadOS. The keyWindow
property cannot reliably identify a specific window in a multi-window environment.
To find the appropriate window for presenting view controllers or other UI-related tasks, you can use the connectedScenes
API to fetch the current scene and its associated window.
1if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {2 let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow })3 // Use 'keyWindow' as needed4}
This code snippet fetches the first connected UIWindowScene and then finds the key window among its windows.
In iOS 15 and later, you can use a more streamlined approach:
1let keyWindow = UIApplication.shared.connectedScenes2 .compactMap { $0 as? UIWindowScene }3 .flatMap { $0.windows }4 .first(where: { $0.isKeyWindow })
This code iterates over all connected scenes, filters for UIWindowScenes, and then looks for the key window.