【Swift】Google Admob 8.2 でインタースティシャル広告を貼る方法【iOS】
初めに
iOS向けの Google Mobile Ads SDK 8.2.0 が2021年3月12日にリリースされました。
私は今までバージョン7のSDKを使用していましたが、バージョンアップによって、微妙に動かなくなったので、バージョン8への対応について記載したいと思います。
ソースコードの編集
インタースティシャル広告を貼るために、まずはAppDelegate.swiftです。赤字部分が追記したところです。
AppDelegate.swift
import GoogleMobileAds
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GADMobileAds.sharedInstance().start(completionHandler: nil)
return true
}
}
つぎにViewController.swiftです。
インタースティシャル広告は、画面が遷移する際に全画面に表示させる広告ですので、私は遷移元のViewControllerに仕込んでいます。アプリの利用者がインタースティシャル広告を閉じた時に次の画面に遷移(正確には次の行が実行)されます。
ここでのポイントは GADInterstitialDelegate が廃止されて GADFullScreenContentDelegate に変更されたところです。
また、info.plistに AdMobTest というBoolean型でテスト用とリリース用のIDを切り替えています。
ViewController.swift
import GoogleMobileAds
class ViewController: UIViewController, UINavigationControllerDelegate, UITextViewDelegate, GADBannerViewDelegate, GADFullScreenContentDelegate {
// Interstitial for release
let AdMobInterstitialID: String = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx"
// Interstitial for test
let TestInterstitialID: String = "ca-app-pub-3940256099942544/4411468910"
// Interstitial
var interstitialAd: GADInterstitialAd!
// for debug
let AdMobTest : Bool = Bundle.main.object(forInfoDictionaryKey: "AdMobTest") as! Bool
override func viewDidLoad() {
super.viewDidLoad()
let interstitialAdUnitID: String
if AdMobTest {
interstitialAdUnitID = TestInterstitialID
}
else{
interstitialAdUnitID = AdMobInterstitialID
}
GADInterstitialAd.load(withAdUnitID: interstitialAdUnitID, request: GADRequest()) { ad, error in
if error != nil { return }
self.interstitialAd = ad
self.interstitialAd.fullScreenContentDelegate = self
}
}
func hoge() {
// admob インタースティシャルを表示
do {
try interstitialAd.canPresent(fromRootViewController: self)
self.interstitialAd.present(fromRootViewController: self)
} catch {
// 広告を表示しない
}
}
参考情報
まずは 公式のガイド(英語版)を読むのが良いと思います。日本語版は更新が遅いので、最新の情報は常に英語版を見る必要があります。
developers.google.com
最後に
今回は、iOS向けの Google Mobile Ads SDK 8.2.0 でインタースティシャル広告を貼る方法について記載しました。
参考になれば幸いです。参考になったと思われた方は広告クリックをお願いします。