1

I want to get rid of the " 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" message in my function (my function works very well by the way.).

The line of code involved:

banner.rootViewController = UIApplication.shared.windows.first?.rootViewController

How can i do that?

My function :

struct AdView : UIViewRepresentable {
    func makeUIView(context: UIViewRepresentableContext<AdView>) -> GADBannerView {
        let banner = GADBannerView(adSize: kGADAdSizeBanner)
        banner.adUnitID = "ca-app-pub-3940256099942544/2934735716" // test ad
                banner.rootViewController = UIApplication.shared.windows.first?.rootViewController
        banner.load(GADRequest())
        return banner
    }
    
    func updateUIView(_ uiView: GADBannerView, context: UIViewRepresentableContext<AdView>) {}
}

I tried that but it's not working :

banner.rootViewController = UIApplication.shared.connectedScenes.first?.rootViewController

Thanks

Flincorp
  • 521
  • 4
  • 18

1 Answers1

8

You can use following as UIApplication.shared.currentUIWindow()?.rootViewController

public extension UIApplication {
    func currentUIWindow() -> UIWindow? {
        let connectedScenes = UIApplication.shared.connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .compactMap { $0 as? UIWindowScene }
        
        let window = connectedScenes.first?
            .windows
            .first { $0.isKeyWindow }

        return window
        
    }
}
cluelessCoder
  • 590
  • 3
  • 18
  • Ummmm did you forget to declare filteredScene??? I got a "Cannot find 'filteredScene' in scope" – Flincorp Oct 22 '21 at 22:35
  • Thank you for the catch! Correct now, I've just copied the code I'm using via iPad (with some simplification) and forgot to remove it. – cluelessCoder Oct 23 '21 at 10:05