0

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

涉及的代码行:

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

我怎样才能做到这一点?

我的功能:

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>) {}
}

我试过了,但它不工作:

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

谢谢

4

1 回答 1

4

您可以使用以下作为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
        
    }
}
于 2021-10-22T21:41:32.630 回答