Admob Crashing App when final Ads are implemented - SwiftUI

203 Views Asked by At

Trying to implement AdMob on my iOS/SwiftUI app. Chose the BannerAd style, implemented it in a few screens. Have been using the test ads, as per admob guidelines, for a while, with no issues. However, now that I want to implement the real ads and I change the unitID for the AdMob key, my app crashes in Testflight. This is weird, because it works in XCode's test devices and my device in test mode. When I search the internet, most solutions are either for Android or Interstitial Ads...

Banner Ad Backend

import SwiftUI
import GoogleMobileAds

struct BannerAd: UIViewRepresentable {
    var unitID: String
    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }
    func makeUIView(context: Context) -> GADBannerView{
        let adView = GADBannerView(adSize: GADAdSizeBanner)
        adView.adUnitID = unitID
        adView.rootViewController = UIApplication.shared.getRootViewController()
        adView.delegate = context.coordinator
        adView.load(GADRequest())
        return adView
    }
    func updateUIView(_ uiView: GADBannerView, context: Context) {
    }
    class Coordinator: NSObject,GADBannerViewDelegate{
        func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
          print("bannerViewDidReceiveAd")
        }

        func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
          print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
        }

        func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
          print("bannerViewDidRecordImpression")
        }

        func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
          print("bannerViewWillPresentScreen")
        }

        func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
          print("bannerViewWillDIsmissScreen")
        }

        func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
          print("bannerViewDidDismissScreen")
        }
    }
    
}
extension UIApplication{
    func getRootViewController()->UIViewController{
        guard let screen = self.connectedScenes.first as? UIWindowScene else{
            return .init()
        }
        
        guard let root = screen.windows.first?.rootViewController else{
            return .init()
        }
        
        return root
    }
}

The Banner Ad implementation Example:

import SwiftUI
import MessageUI
import AppTrackingTransparency

struct PatientsView: View {
    
    [...]   
            ScrollView(){
            BannerAd(unitID: "ca-app-pub-numbers")
                    .frame(maxHeight: 50)
                VStack(alignment:.leading){
                    [...]
                }
                    Spacer()
                    Spacer()
                }
                .padding(.top, 30.0)
            }
        
        }
}

0

There are 0 best solutions below