You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决iOS15下AdMob横幅广告出现的'windows'已弃用警告

解决方案

你之前的修改未生效是因为 UIApplication.shared.connectedScenes.first 返回的是泛用的 UIScene 类型,本身没有 rootViewController 属性,需要先将其转换为 UIWindowScene 类型后再访问窗口相关属性。

你可以直接替换问题代码行为以下内容:

banner.rootViewController = UIApplication.shared.connectedScenes
    .filter { $0.activationState == .foregroundActive }
    .compactMap { $0 as? UIWindowScene }
    .first?.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.connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .compactMap { $0 as? UIWindowScene }
            .first?.windows
            .first?.rootViewController
        banner.load(GADRequest())
        return banner
    }
    
    func updateUIView(_ uiView: GADBannerView, context: UIViewRepresentableContext<AdView>) {}
}

上述代码额外增加了前台活跃场景过滤逻辑,能避免误取后台场景导致取值为空的问题,适配单场景iPhone应用和多场景iPad应用,完全消除iOS15及以上版本的弃用告警,原有功能逻辑保持不变。

内容的提问来源于stack exchange,提问作者Flincorp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:15:03