SwiftUI Admob

2020年11月6日

SwiftUIでAdMobを実装する方法

Info.plistを編集する

  • Key: GADApplicationIdentifier
  • Type: String
  • Value: ca-app-pub-xxx

import SwiftUI
// import文を追加する
import UIKit
import GoogleMobileAds

// AppDelegateクラスを定義する
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // Mobile Ads SDKを初期化する
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        return true
    }
}

@main
struct DemoApp: App {
    // SwiftUI AppライフサイクルにAppDelegateクラスを注入する
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

バナーを実装する

import SwiftUI
import GoogleMobileAds

struct AdView: UIViewRepresentable {
    func makeUIView(context: Context) -> GADBannerView {
        let banner = GADBannerView(adSize: kGADAdSizeBanner)
        // 以下は、バナー広告向けのテスト専用広告ユニットIDです。自身の広告ユニットIDと置き換えてください。
        banner.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        banner.rootViewController = UIApplication.shared.windows.first?.rootViewController
        banner.load(GADRequest())
        return banner
    }

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

struct ContentView: View {
    var body: some View {
        AdView()
        // サイズを変更する場合
        // AdView().frame(width: 320, height: 50)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

AdMobのNative AdsをSwiftUIで表示する – Qiita

NativeAdsViewController.swift
NativeAdsViewController.swift
import SwiftUI
import Combine

final class NativeAdsViewController: NSObject, UIViewControllerRepresentable {

    final class SizeModel: ObservableObject {
        @Published var width: CGFloat = 355
        @Published var height: CGFloat = 370
    }

    var adLoader: GADAdLoader?
    var templateView: GADTMediumTemplateView?

    let adUnitID: String
    let sizeModel: SizeModel

    private var cancellables = Set()

    init(adUnitID: String, sizeModel: SizeModel) {
        self.adUnitID = adUnitID
        self.sizeModel = sizeModel
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIViewController {

        let templateView = GADTMediumTemplateView()
        self.templateView = templateView

        let viewController = UIViewController()

        viewController.view.addSubview(templateView)
        templateView.addHorizontalConstraintsToSuperviewWidth()
        templateView.addVerticalCenterConstraintToSuperview()

        subscribeUpdateSizeModel()

        #if DEBUG
        let nativeAdvanced = "ca-app-pub-3940256099942544/3986624511"
//        let nativeAdvancedVideo = "ca-app-pub-3940256099942544/2521693316"

        let adUnitID = nativeAdvanced
        #else
        let adUnitID = self.adUnitID
        #endif

        let rootViewController = UIApplication.shared.windows.first?.rootViewController
        let loader = GADAdLoader(adUnitID: adUnitID, rootViewController: rootViewController, adTypes: [GADAdLoaderAdType.unifiedNative], options: nil)
        loader.delegate = self

        adLoader = loader

        loader.load(GADRequest())

        return viewController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext) {}

    private func subscribeUpdateSizeModel() {
        templateView?.publisher(for: \.bounds)
            .sink(receiveValue: { (bounds) in
                self.sizeModel.width = bounds.width
                self.sizeModel.height = bounds.height
            })
            .store(in: &cancellables)
    }
}

extension NativeAdsViewController: GADUnifiedNativeAdLoaderDelegate {

    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd) {
        templateView?.nativeAd = nativeAd
    }

    func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: GADRequestError) {}
}