0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUIにAdmobの起動時広告を実装

Last updated at Posted at 2023-06-05

以下はアプリを起動した直後と以降は1時間以上アプリを離れて再度アプリに戻ると表示するやり方です。

AdmobAppOpenAd.swift
import UIKit
import GoogleMobileAds
@main
class AdmobAppOpenAd: NSObject, UIApplicationDelegate, GADFullScreenContentDelegate {
    var appOpenAd: GADAppOpenAd?
    let adRequest = GADRequest()
    let adUnitID = "ca-app-pub-3940256099942544/5662855259"//Test
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//       adomob初期化
        GADMobileAds.sharedInstance().start(completionHandler:{_ in
//        起動時に表示
            self.showAdIfNeeded()
        })
        return true
    }
    func sceneWillEnterForeground(_ scene: UIScene) {
        let interval = getElapsedTimeInSeconds()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.008) {
//この遅延が無いとなぜが開いてすぐ閉じてしまう
//      閉じていた時間が1時間以上、4時間未満のとき (4時間で広告の使用可能期限切れ)
            if interval > 3600 , interval < 13500 {
                self.showAdIfNeeded()
            }
        }
    }
    func sceneDidEnterBackground(_ scene: UIScene) {
//        バックグラウンドに入る時にプリロード
        preloadAppOpenAd()
//        バックグラウンドに入った時間を保存
        saveCurrentTime()
    }
    func presentAppOpenAd(from rootViewController: UIViewController) {
        if self.appOpenAd != nil  {
            self.appOpenAd?.fullScreenContentDelegate = self
            self.appOpenAd?.present(fromRootViewController: rootViewController)
        } else {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
                return
            }
            GADAppOpenAd.load(withAdUnitID: adUnitID, request: adRequest, orientation: windowScene.interfaceOrientation) { [weak self] (ad, error) in
                if let error = error {
                    print("Failed to load App Open ad: \(error)")
                    return
                }
                self?.appOpenAd = ad
                self?.appOpenAd?.fullScreenContentDelegate = self
                self?.appOpenAd?.present(fromRootViewController: rootViewController)
                print("AppOpen ad show")
            }
        }
    }
    func showAdIfNeeded() {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let keyWindow = windowScene.windows.first,
              let rootViewController = keyWindow.rootViewController else {
            print("ルートビューコントローラーが見つかりません")
            return
        }
        presentAppOpenAd(from: rootViewController)
    }
    func preloadAppOpenAd() {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
            print("Failed to load App Open windowScene")
            return
        }
        GADAppOpenAd.load(withAdUnitID: adUnitID, request: adRequest, orientation: windowScene.interfaceOrientation) { [weak self] (ad, error) in
            if let error = error {
                print("Failed to load App Open ad: \(error)")
                return
            }
            self?.appOpenAd = ad
            print("App Open ad preloaded")
        }
    }
    var savedTime: Date?
    // 現在時間を保存するメソッド
    func saveCurrentTime() {
        let currentTime = Date()
        self.savedTime = currentTime
    }
    
    // 保存時間から経過した時間を秒数で返すメソッド
    func getElapsedTimeInSeconds() -> TimeInterval {
        guard let savedTime = self.savedTime else {
            return 0
        }
        
        let currentTime = Date()
        let elapsedTime = currentTime.timeIntervalSince(savedTime)
        return max(elapsedTime, 0)
    }
    // MARK: - GADFullScreenContentDelegate
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
//       ここにプリロードを入れても初回起動時の広告を閉じたときは無効になる
    }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?