Featured image of post Hello Admob

Hello Admob

How to implement Admob for SwiftUI

Introduction

AdMob is a popular mobile advertising platform developed by Google that helps developers monetize their mobile apps. In this blog post, we’ll walk through the steps to implement AdMob in a SwiftUI.

Prerequisites

  • Xcode: Ensure you have the latest version of Xcode installed on your development machine.
  • Google AdMob Account: Create an AdMob account if you don’t have one already.
  • iOS App Project: Have a SwiftUI-based iOS app project ready for integration.

Steps to Implement AdMob

Set Up Your AdMob Account

  • Log in to your AdMob account.
  • Create an AdMob app.
  • Select the platform (iOS) and provide the required details for your app (app name, etc.).
  • Create 5 ad units for the new app. The result will be as follows: Ad units

Integrating the AdMob SDK

  • Search for the Google Mobile Ads Swift Package GitHub repository and select the version of the Google Mobile Ads Swift Package you want to use:
1
https://github.com/googleads/swift-package-manager-google-mobile-ads.git
  • Updating Info.plist. Add two keys to your Info.plist file:

    • GADApplicationIdentifier: Your AdMob app ID.
    • SKAdNetworkItems key with SKAdNetworkIdentifier values for Google. More detail at link.
  • Manually add the -ObjC linker flag to Other Linker Flags in your target’s build settings even if you’re using CocoaPods or Swift Package Manager. Adding the -ObjC linker flag

Initializing the SDK

  • AppDelegate: Initialize GADMobileAds in your app’s AppDelegate file:
1
2
3
4
5
6
import GoogleMobileAds

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    GADMobileAds.sharedInstance().start(completionHandler: nil)
    return true
}
  • Main App View: Initialize it within the init function of your main app view:
1
2
3
4
5
6
7
8
import GoogleMobileAds

struct MyAppView: View {
    init() {
        GADMobileAds.sharedInstance().start(completionHandler: nil)
    }
    // ... rest of your view code
}

Creating a Custom View for Banner Ads

  • Create a BannerAdViewController
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import UIKit
import GoogleMobileAds

final class BannerAdViewController: UIViewController {
  private let bannerView: GADBannerView = GADBannerView()
  private let adUnitId: String
  
  init(adUnitId: String) {
    self.adUnitId = adUnitId
    super.init(nibName: nil, bundle: nil)
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    bannerView.adUnitID = adUnitId
    bannerView.rootViewController = self
    view.addSubview(bannerView)
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadBannerAd()
  }
  
  override func viewWillTransition(
    to size: CGSize,
    with coordinator: UIViewControllerTransitionCoordinator
  ) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(
      alongsideTransition: { _ in },
      completion: { _ in
        self.loadBannerAd()
      }
    )
  }
  
  private func loadBannerAd() {
    let frame = view.frame.inset(by: view.safeAreaInsets)
    let viewWidth = frame.size.width
    
    bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
    bannerView.load(GADRequest())
  }
}
  • Create a BannerAdViewControllerRepresentable
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import SwiftUI

struct BannerAdViewControllerRepresentable: UIViewControllerRepresentable {
  typealias UIViewControllerType = BannerAdViewController
  
  private let adUnitId: String
  
  init(adUnitId: String) {
    self.adUnitId = adUnitId
  }
  
  func makeUIViewController(context: Context) -> UIViewControllerType {
    return BannerAdViewController(adUnitId: adUnitId)
  }
  
  func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
}
  • Create a BannerAdView
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import SwiftUI
import GoogleMobileAds

public struct BannerAdView: View {
  @State private var height: CGFloat = .zero
  @State private var width: CGFloat = .zero
  
  private let adUnitId: String
  
  public var body: some View {
    BannerAdViewControllerRepresentable(adUnitId: adUnitId)
      .frame(width: width, height: height)
      .onAppear {
        setFrame()
      }
      .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
        setFrame()
      }
  }
  
  public init(adUnitId: String) {
    self.adUnitId = adUnitId
  }
  
  private func setFrame() {
    let safeAreaInsets = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.safeAreaInsets ?? .zero
    let frame = UIScreen.main.bounds.inset(by: safeAreaInsets)
    
    let adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.width)
    self.width = adSize.size.width
    self.height = adSize.size.height
  }
}
  • How to use Banner Admob
1
2
3
4
5
6
7
8
9
struct HomeView: View {
  var body: some View {
    VStack(spacing: 0) {
      // Your rest code ...
      BannerAdView(adUnitId: Constants.bannerAdUnitId)
      // Your rest code ...
    }
  }
}

References

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy