2

I have project in SwiftUI 2.0 but when I update to SwiftUI 3.0 it is throw an error for

windows

as a

windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

any idea?

.padding(.top, UIApplication.shared.windows.first?.safeAreaInsets.top)

2 Answers2

11

Well, the warning message reflects the essence of the problem pretty fully.

Apple really deprecated UIApplication.shared.windows, so to fix your warning, instead of UIApplication.shared.windows.first? you should use:

UIApplication
.shared
.connectedScenes
.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }
.first { $0.isKeyWindow }

Then, your .padding view modifier will look like this:

.padding(.top, UIApplication
                    .shared
                    .connectedScenes
                    .flatMap { ($0 as? UIWindowScene)?.windows ?? [] }
                    .first { $0.isKeyWindow }?.safeAreaInsets.top)
alexandrov
  • 363
  • 3
  • 11
  • 2
    I see this answer all over stack overflow and it is simply a bad solution for any app that supports more than one scene. And that includes any iPad add that supports multitasking. This code grabs a random scene instead of the scene specific to the view in question. – HangarRash May 09 '23 at 15:15
1

I saw this code from an apple answer

If you have a view, the easiest way to access the key window of your scene is to call

view.window.windowScene?.keyWindow

https://developer.apple.com/forums/thread/682621

devjme
  • 684
  • 6
  • 12