Google AdMob integration in SwiftUI

后端 未结 3 1636
春和景丽
春和景丽 2021-01-01 02:56

I found nowhere an example how to integrate it with swiftui. Does anybody found a tutorial? The problem is the part with the root controller.

3条回答
  •  自闭症患者
    2021-01-01 03:16

    You should use UIViewRepresentable instead of UIViewControllerRepresentable.

    I implemented the Adaptive banner with this code:

    struct AdView : UIViewRepresentable {
        @State private var banner: GADBannerView = GADBannerView(adSize: kGADAdSizeBanner)
        
        func makeUIView(context: UIViewRepresentableContext) -> GADBannerView {
            #if DEBUG
            banner.adUnitID = "ca-app-pub-debug"
            #else
            banner.adUnitID = "ca-app-pub-prod"
            #endif
    
            guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else {
                return banner
            }
            
            banner.rootViewController = rootViewController
            
            let frame = { () -> CGRect in
                return banner.rootViewController!.view.frame.inset(by: banner.rootViewController!.view.safeAreaInsets)
            }()
            let viewWidth = frame.size.width
    
            banner.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
    
            banner.load(GADRequest())
            return banner
        }
        
        func updateUIView(_ uiView: GADBannerView, context: UIViewRepresentableContext) {
        }
    }
    

    Then you can call on your Stack using

    AdView().frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 300)
                    .frame(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)
    

提交回复
热议问题