iPad 容器 Window 上的 Admob 崩溃不应为零

Admob crash on iPad with Window container should not be nil

我正在尝试整合 Admob。 SDK 版本为 9.0.

我从

复制了代码

https://medium.com/geekculture/adding-google-mobile-ads-admob-to-your-swiftui-app-in-ios-14-5-5073a2b99cf9

它在 iPhone 设备和 iPad 模拟器上运行良好。但是,它在 iPad 设备 iOS 15.

上崩溃

错误日志为

*** Assertion failure in -[GADOMIDStateWatcher adSessionDidBecomeActive:], GADOMIDStateWatcher.m:75

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Window container should not be nil'

它看起来像 Admob 上的错误,我不确定。

有没有其他和我一样的问题?你解决了那个问题吗?

我遇到了同样的问题。将 AdMob SDK 降级到 8.13.0 似乎可以解决问题。

终于找到问题并修复如下。

extension UIApplication {
    
    var keyWindow: UIWindow? {
        // Get connected scenes
        return UIApplication.shared.connectedScenes
            // Keep only active scenes, onscreen and visible to the user
            .filter { [=10=].activationState == .foregroundActive }
            // Keep only the first `UIWindowScene`
            .first(where: { [=10=] is UIWindowScene })
            // Get its associated windows
            .flatMap({ [=10=] as? UIWindowScene })?.windows
            // Finally, keep only the key window
            .first(where: \.isKeyWindow)
    }
    
}

来自

的 UIApplication 扩展代码
func loadBannerAd() {
        let frame = view.frame.inset(by: view.safeAreaInsets)
        let viewWidth = frame.size.width

        //Updates the BannerView size relative to the current safe area of device (This creates the adaptive banner)
        bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

        let request = GADRequest()
if let scene = UIApplication.shared.keyWindow?.rootViewController?.view.window?.windowScene {
            request.scene = scene
        }
        
        bannerView.load(request)
    }

主要问题是

我需要在请求中设置场景

let request = GADRequest()
if let scene = UIApplication.shared.keyWindow?.rootViewController?.view.window?.windowScene {
            request.scene = scene
}

之后,在 iPad 上工作正常。