iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌊

Displaying AdMob Banner Ads in SwiftUI

に公開

I implemented AdMob banner ads in my SwiftUI app, referring to the method introduced in this article.
https://qiita.com/am10/items/008d1314c1e4df18ab75

I was able to display the banner like this:

Since my app uses Firebase and SwiftUI, the steps were slightly different. Here are the implementation steps when using Firebase:
https://firebase.google.cn/docs/admob/ios/quick-start?hl=ja

Import the Mobile Ads SDK

I added the following to my CocoaPods:

pod 'Firebase/Analytics'
pod 'Firebase/AdMob'

Update Info.plist

Add the following key/value pair to Info.plist:

<key>GADApplicationIdentifier</key>
<string>YOUR_APP_ID</string>

Initialize Mobile Ads

To initialize the ads, you need to call GADMobileAds.start() at startup. Here is the example implementation code for initialization as described in the documentation:

import Firebase
...

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Use Firebase library to configure APIs.
    FirebaseApp.configure()

    // Initialize the Google Mobile Ads SDK.
    GADMobileAds.sharedInstance().start(completionHandler: nil)

    return true
  }

}

In a SwiftUI project generated with Xcode 12, the struct marked with @main serves as the app's entry point, so I added an init() and wrote the initialization code there.

import SwiftUI
import Firebase

@main
struct MyApp: App {
    init() {
        FirebaseApp.configure()
        GADMobileAds.sharedInstance().start(completionHandler: nil)
    }
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Displaying the Banner

A class called GADBannerView, which inherits from UIView, is provided for displaying banner ads. Since UIView cannot be displayed directly in SwiftUI, I confirmed two ways to display it by referring to the following sites:

https://reasonable-code.com/swiftui-admob/

https://www.yururiwork.net/swiftuiでadmobバナー広告を表示する/

UIViewRepresentable

This method involves wrapping GADBannerView using UIViewRepresentable. Since you need to specify the rootViewController of the GADBannerView, I retrieved the rootViewController from UIApplication.

struct AdmobBannerView: UIViewRepresentable {
    func makeUIView(context: Context) -> GADBannerView {
        let view = GADBannerView(adSize: kGADAdSizeBanner)
        #if DEBUG
        view.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        #else
        view.adUnitID = "..."
        #endif
        view.rootViewController = UIApplication.shared.windows.first?.rootViewController
        view.load(GADRequest())
        return view
    }

    func updateUIView(_ uiView: GADBannerView, context: Context) {
    }
}

UIViewControllerRepresentable

This method involves displaying GADBannerView inside a UIViewController using UIViewControllerRepresentable.

struct AdmobBannerViewController: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> some UIViewController {
        let view = GADBannerView(adSize: kGADAdSizeBanner)
        #if DEBUG
        view.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        #else
        view.adUnitID = "..."
        #endif
        let viewController = UIViewController()
        viewController.view.addSubview(view)
        viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
        view.rootViewController = viewController
        view.load(GADRequest())
        return viewController
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
    }
}

To integrate it into a View, do the following:

AdmobBannerView().frame(width: 320, height: 50)

Conclusion

These were the steps to display banners using AdMob in a SwiftUI app with Firebase. This is the app where I actually added the ads:
https://apps.apple.com/jp/app/id1541364743

Discussion