'Admob crash on iPad with Window container should not be nil

I am trying to integrate Admob. SDK version is 9.0.

I copied the code from

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

It's working fine on iPhone Device and iPad Simulator. However, it crash on iPad Device with iOS 15.

The error log is

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

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

It look like bugs on Admob and I am not sure about that.

Is there any other same issues like me before ? Did you fix that issue ?

enter image description here enter image description here enter image description here



Solution 1:[1]

I had the same problem. Downgrading the AdMob SDK to 8.13.0 seems to fix the problem.

Solution 2:[2]

Finally found the issue and fixed like following.

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

UIApplication extension code from https://stackoverflow.com/a/68989580/215939

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

The main problem is

I need to set the scene in request

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

After that , working fine on the iPad.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan M
Solution 2 saturngod