最近、初めて GoogleAdMob のインタースティシャル広告を実装しました。笑
先週はバナー広告の設置についての記事を書いたので、ついでにインタースティシャル広告も書きたいと思います ( ̄・ω・ ̄)
CocoaPodsでのインストール 〜 アプリIDの作成
これはバナー広告の設置で書いてるので、そちらをご覧ください。
アプリID の作成までは終わってる前提で進めます。
GoogleMobileAds を扱うクラスを作成
前回のバナー広告の設置の記事で作成したクラスに追記できる形です。
が、この記事はインタースティシャル広告がメインなので、バナー関連のコードは省かせていただきますぜ (∩^o^)⊃━☆゜.*
import GoogleMobileAds
class AdMobHelper: NSObject {
static let shared = AdMobHelper()
private var interstitial: GADInterstitial!
private var interstitialDismissCompletion: (() -> ())?
func initSDK() {
GADMobileAds.sharedInstance().start(completionHandler: nil)
self.interstitial = self.setupInterstital()
}
private func setupInterstital() -> GADInterstitial {
var newInterstitial: GADInterstitial!
#if DEBUG
newInterstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
#else
newInterstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
#endif
newInterstitial.delegate = self
newInterstitial.load(GADRequest())
return newInterstitial
}
func showInterstitial(rootVC: UIViewController, completion: (() -> ())?) {
self.interstitialDismissCompletion = completion
guard self.interstitial.isReady else {
self.interstitialDismissCompletion?()
return
}
self.interstitial.present(fromRootViewController: rootVC)
}
}
//MARK: - GADInterstitialDelegate
extension AdMobHelper: GADInterstitialDelegate {
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
self.interstitial = self.setupInterstital()
self.interstitialDismissCompletion?()
}
}
作成したクラスを使用する
AppDelegate で初期化
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AdMobHelper.shared.initSDK()
return true
}
}
インタースティシャル広告を表示
class ViewController: UIViewController {
override func viewDidLoad() {}
override func viewDidAppear(_ animated: Bool) {
AdMobHelper.shared.showInterstitial(rootVC: self) { [weak self] in
// インタースティシャル広告を閉じた時の処理
}
}
}
viewDidAppear に書きました!テキトーだぜ (m9^ω’)
まぁ表示したい場所に書いてくれたら的な。
さいごに
次からはコピペで表示や… _:(´ཀ`」 ∠):_
違うよ!とかこういう方法あるよ!ってのがあれば教えてください。
では( ¯·ω·¯ )



コメント