Google AdMob integration in SwiftUI

后端 未结 3 1635
春和景丽
春和景丽 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:20

    in the Apple SwiftUI tutorial - integration in SwiftUI

    you can find that how to solve this question with UIViewControllerRepresentable

    and I create an example like this

    import GoogleMobileAds
    import SwiftUI
    import UIKit
    
    struct GADBannerViewController: UIViewControllerRepresentable {
        func makeUIViewController(context: Context) -> UIViewController {
            let view = GADBannerView(adSize: kGADAdSizeBanner)
            let viewController = UIViewController()
            view.adUnitID = "your ad unit id in there."
            view.rootViewController = viewController
            viewController.view.addSubview(view)
            viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
            view.load(GADRequest())
            return viewController
        }
    
        func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
    }
    

    then you can using GADBannerViewController in your SwiftUI view's body like that

    HStack {
        Spacer()
        GADBannerViewController()
            .frame(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)
        Spacer()
    }
    

    if you have any questions, please let me know.

提交回复
热议问题