Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google AdMob integration in SwiftUI

Tags:

swiftui

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.

like image 975
Ben Keil Avatar asked Aug 24 '19 21:08

Ben Keil


2 Answers

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.👌

like image 85
張家齊 Avatar answered Oct 20 '22 05:10

張家齊


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

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)
like image 45
mcatach Avatar answered Oct 20 '22 05:10

mcatach