Google AdMob integration in SwiftUI

2020-02-26 13:10发布

问题:

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.

回答1:

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.

标签: swiftui