User 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene insteadの対処法
公開日: 2023-09-24 11:25:59
更新日: 2023-09-26 01:08:01
iOS 15.0 での重要な変更の1つに、UIApplication.shared.windows の使用が非推奨になった点があります。この変更は、マルチウィンドウサポートの拡張を反映したものです。この記事では、この変更に対応する方法を解説します。
背景: なぜ変更が行われたのか?
iOS 13からAppleはiPadOSを導入し、マルチウィンドウサポートを強化してきました。これにより、アプリケーションは複数のウィンドウを持つことが可能になり、それぞれのウィンドウは独自のシーン(UIWindowScene)に関連付けられます。従来のUIApplication.shared.windowsのアプローチは、この新しいマルチウィンドウ環境を適切に考慮していなかったため、非推奨となりました。
新しいアプローチ: UIWindowScene.windowsを使う
iOS 15.0以降、UIWindowScene.windows を使用して特定のシーンに関連するウィンドウの集合にアクセスする方法が推奨されています。
以下は、旧方法と新方法の比較です:
旧方法:
if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
// 何かの処理
}
新方法:
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
if let window = windowScene.windows.first(where: { $0.isKeyWindow }) {
// 何かの処理
}
}
新しいアプローチでは、まず接続されたシーンの中からUIWindowSceneを取得します。次に、そのシーン内のウィンドウの中からキーウィンドウを探します。
まとめ
iOS 15.0の変更に適応するためには、アプリケーションのウィンドウ取得方法を更新する必要があります。UIWindowScene.windowsの使用を始めることで、新しいマルチウィンドウ環境でも適切に動作するアプリケーションを実現できます。
追記 別パターン
変更前
if let rootVC = UIApplication.shared.windows.first?.rootViewController {
adManager.showAd(from: rootVC) { success in
if success {
print("Ad was shown successfully")
} else {
print("Failed to show the ad")
}
}
}変更後
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let rootVC = windowScene.windows.first?.rootViewController {
adManager.showAd(from: rootVC) { success in
if success {
print("Ad was shown successfully")
} else {
print("Failed to show the ad")
}
}
}