如何使用 AdMob 横幅消除消息“'windows' 在 iOS 15.0 中已弃用:在相关窗口场景上使用 UIWindowScene.windows”?

Fli*_*orp 5 admob rootviewcontroller swiftui uiwindowscene

我想摆脱我的函数中的“‘windows’在 iOS 15.0 中已弃用:在相关窗口场景上使用 UIWindowScene.windows”消息(顺便说一下,我的函数运行得很好。)。

涉及的代码行:

banner.rootViewController = UIApplication.shared.windows.first?.rootViewController
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

我的职能:

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>) {}
}
Run Code Online (Sandbox Code Playgroud)

我尝试过,但它不起作用:

banner.rootViewController = UIApplication.shared.connectedScenes.first?.rootViewController
Run Code Online (Sandbox Code Playgroud)

谢谢

clu*_*der 17

您可以使用以下作为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
        
    }
}
Run Code Online (Sandbox Code Playgroud)