Skip to content
DeveloperMemos

Resolving 'keyWindow' Deprecation in iOS 13.0

iOS, Swift, iOS 13, UIWindow1 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.

Understanding the 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.

Alternative to 'keyWindow'

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.

For iOS 13 and Above

1if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
2 let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow })
3 // Use 'keyWindow' as needed
4}

This code snippet fetches the first connected UIWindowScene and then finds the key window among its windows.

For iOS 15 and Above

In iOS 15 and later, you can use a more streamlined approach:

1let keyWindow = UIApplication.shared.connectedScenes
2 .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.

Some Best Practices

  • Check for Scene Support: Always check whether your app supports multiple scenes before fetching the key window.
  • Avoid Hardcoding: Avoid hardcoding window references; always fetch the key window dynamically.
  • Scene Lifecycle Awareness: Be aware of the scene lifecycle and how it may affect window visibility and interactivity.