Home > AI > IOS >

integrate Google AdMob into IOS

Step 1: get ad id from Google AdMob

1-1) Create an App, you have an App ID

Add these two entries in the info.plist

<key>GADApplicationIdentifier</key>
  <string>{your App ID}</string>
<key>SKAdNetworkItems</key>
  <array>
    <dict>
      <key>SKAdNetworkIdentifier</key>
      <string>cstr6suwn9.skadnetwork</string>
    </dict>
  </array>

1-2) Create an Ad Unit, you have an Ad Unit ID.

Step 2: install the SDK

$ pod init
$ vi PodFile
add pod 'Google-Mobile-Ads-SDK' 
$ pod install --repo-update

Step 3: write the code.

Main.swift

import SwiftUI
import GoogleMobileAds

@main
struct GoodApp: App {
    
    init() {
        GADMobileAds.sharedInstance().start(completionHandler: nil)
    }
    
    var body: some Scene {
        WindowGroup {
            SettingView()
                .environmentObject(HomeGlobal())
        }
    }
}

TestAdView.swift

struct TestAdView: UIViewControllerRepresentable {
    @EnvironmentObject var home: HomeGlobal
    
    
    func makeUIViewController(context: Context) -> some UIViewController {
        let vc = UIViewController()
        
        let banner = GADBannerView()
        banner.adUnitID = "{your ad unit id}"
        banner.rootViewController = vc
        banner.load(GADRequest())
        banner.frame = CGRect(x: 0,
                              y: home.screenHeight - 50,
                              width: home.screenWidth,
                              height: 50)
        vc.view.addSubview(banner)
        
        return vc
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
}

ContentView.swift

struct ContentView: View {
    var body: some View {
        TestAdView()
    }
}

Leave a Reply