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

3

There are 3 best solutions below

4
On BEST ANSWER

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
        
    }
}
1
On

In Objective C I was able to replace:

NSArray  *windows = [[UIApplication sharedApplication] windows];

with

NSArray *scenes=[[[UIApplication sharedApplication] connectedScenes] allObjects];
NSArray *windows=[[scenes objectAtIndex:0] windows];

My full method is:

-(UIViewController *)parentController {
    
    UIWindow *foundWindow = nil;
    NSArray *scenes=[[[UIApplication sharedApplication] connectedScenes] allObjects];
    NSArray *windows=[[scenes objectAtIndex:0] windows];
    for (UIWindow  *window in windows) {
        if (window.isKeyWindow) {
            foundWindow = window;
            break;
        }
    }
    UIViewController* parentController = foundWindow.rootViewController;
    while( parentController.presentedViewController &&
          parentController != parentController.presentedViewController ){
        parentController = parentController.presentedViewController;
    }
    return  parentController;
}
1
On

For swift UI simply create a constant

  struct SceneConstants {
        static let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
    }