LoginSignup
13
5

【SwiftUI】インタースティシャル広告の表示方法

Last updated at Posted at 2022-05-10

第0部: スタートガイド

第1部: リワード広告
第2部: インタースティシャル広告 ← イマココ
第3部: ネイティブ広告
第4部: バナー広告
第5部: アプリ起動広告

はじめに

リワード広告の表示」がちょっと人気だったのでインタースティシャル広告バージョンもやってみました。
投稿ネタ尽きた時用にこれシリーズ化します笑

実装準備

実装の前にスタートガイドに記載してある事を行います

①: Mobile Ads SDK のインポート
②: Info.plist の更新
③: Mobile Ads SDK の初期化

こちらで詳しく解説してあります。
これが終われば準備は完了です。

実装

Interstitial.swift
import GoogleMobileAds

class Interstitial: NSObject, GADFullScreenContentDelegate, ObservableObject {
    @Published var interstitialAdLoaded: Bool = false
    
    var interstitialAd: GADInterstitialAd?

    override init() {
        super.init()
    }

    // リワード広告の読み込み
    func loadInterstitial() {
        GADInterstitialAd.load(withAdUnitID: "ca-app-pub-3940256099942544/4411468910", request: GADRequest()) { (ad, error) in
            if let _ = error {
                print("😭: 読み込みに失敗しました")
                self.interstitialAdLoaded = false
                return
            }
            print("😍: 読み込みに成功しました")
            self.interstitialAdLoaded = true
            self.interstitialAd = ad
            self.interstitialAd?.fullScreenContentDelegate = self
        }
    }

    // インタースティシャル広告の表示
    func presentInterstitial() {
        let root = UIApplication.shared.windows.first?.rootViewController
        if let ad = interstitialAd {
            ad.present(fromRootViewController: root!)
            self.interstitialAdLoaded = false
        } else {
            print("😭: 広告の準備ができていませんでした")
            self.interstitialAdLoaded = false
            self.loadInterstitial()
        }
    }
    // 失敗通知
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        print("インタースティシャル広告の表示に失敗しました")
        self.interstitialAdLoaded = false
        self.loadInterstitial()
    }

    // 表示通知
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        print("インタースティシャル広告を表示しました")
        self.interstitialAdLoaded = false
    }

    // クローズ通知
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        print("インタースティシャル広告を閉じました")
        self.interstitialAdLoaded = false
    }
}
ContentView.swift
import SwiftUI

struct ContentView: View {
    @ObservedObject var interstitial = Interstitial()
    var body: some View {
        Button(action: {
            interstitial.presentInterstitial()
        }) {
            Text(interstitial.interstitialAdLoaded ? "インタースティシャル広告表示" : "読み込み中...")
        }
        .onAppear() {
            interstitial.loadInterstitial()
        }
        .disabled(!interstitial.interstitialAdLoaded)
    }
}

Videotogif (2).gif

おわり

今回作成したプロジェクトを置いとくので参考にしてください。

13
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5