swiftuiadmobrootviewcontrolleruiwindowscene

How to get rid of message " 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" with AdMob banner?


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


Solution

  • 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
            
        }
    }