插頁式獎勵廣告 (Beta 版)

插頁式獎勵廣告是一種獎勵廣告格式,可在應用程式自然轉換時自動顯示這類廣告,向使用者提供獎勵。與獎勵廣告不同的是,插頁式獎勵廣告不需要等使用者確定選擇觀看即可放送。

必要條件

  • Google Mobile Ads SDK 7.60.0 以上版本。
  • 完成入門指南

實作

整合插頁式獎勵廣告的主要步驟如下:

  • 載入廣告
  • [選用] 驗證 SSV 回呼
  • 註冊回呼
  • 顯示廣告並處理獎勵事件

載入廣告

您可以使用 GADRewardedInterstitialAd 類別的 load(adUnitID:request) 方法載入廣告。

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()

    Task {
      do {
        rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
          withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
      } catch {
        print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
      }
    }
  }
}

SwiftUI

import GoogleMobileAds

class RewardedInterstitialViewModel: NSObject, ObservableObject,
  GADFullScreenContentDelegate
{
  @Published var coins = 0
  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  func loadAd() async {
    do {
      rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
        withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
      rewardedInterstitialAd?.fullScreenContentDelegate = self
    } catch {
      print(
        "Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
    }
  }

Objective-C

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) GADRewardedInterstitialAd* rewardedInterstitialAd;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  [GADRewardedInterstitialAd
      loadWithAdUnitID:@"<var label='the ad unit ID'>ca-app-pub-3940256099942544/6978759866</var>"
                request:[GADRequest request]
      completionHandler:^(
          GADRewardedInterstitialAd* _Nullable rewardedInterstitialAd,
          NSError* _Nullable error) {
        if (!error) {
          self.rewardedInterstitialAd = rewardedInterstitialAd;
        }
      }
  ];
}

[選用] 驗證伺服器端驗證 (SSV) 回呼

如果應用程式需要在伺服器端驗證回呼中使用額外資料,則應使用獎勵廣告的客製資料功能。獎勵廣告物件上設定的任何字串值,都會傳遞至 SSV 回呼的 custom_data 查詢參數。如果未設定自訂資料值,SSV 回呼中就不會顯示 custom_data 查詢參數值。

以下程式碼範例示範如何在要求廣告前,在獎勵式插頁廣告物件上設定自訂資料。

Swift

do {
  rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
    withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
  let options = GADServerSideVerificationOptions()
  options.customRewardString = "SAMPLE_CUSTOM_DATA_STRING"
  rewardedInterstitialAd.serverSideVerificationOptions = options
} catch {
  print("Rewarded ad failed to load with error: \(error.localizedDescription)")
}

Objective-C

[GADRewardedInterstitialAd
    loadWithAdUnitID:@"ca-app-pub-3940256099942544/6978759866"
              request:GADRequest
    completionHandler:^(GADRewardedInterstitialAd *ad, NSError *error) {
      if (error) {
        // Handle Error
        return;
      }
      self.rewardedInterstitialAd = ad;
      GADServerSideVerificationOptions *options =
          [[GADServerSideVerificationOptions alloc] init];
      options.customRewardString = @"SAMPLE_CUSTOM_DATA_STRING";
      ad.serverSideVerificationOptions = options;
    }];

註冊回呼

為了接收簡報事件的通知,您必須導入 GADFullScreenContentDelegate 通訊協定,並指派給傳回廣告的 fullScreenContentDelegate 屬性。GADFullScreenContentDelegate 通訊協定會處理廣告呈現成功或失敗,以及廣告關閉時的回呼。下列程式碼顯示如何導入通訊協定,並將其指派給廣告:

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()

    Task {
      do {
        rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
          withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
        self.rewardedInterstitialAd?.fullScreenContentDelegate = self
      } catch {
        print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
      }
    }
  }

  /// Tells the delegate that the ad failed to present full screen content.
  func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
    print("Ad did fail to present full screen content.")
  }

  /// Tells the delegate that the ad will present full screen content.
  func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    print("Ad will present full screen content.")
  }

  /// Tells the delegate that the ad dismissed full screen content.
  func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    print("Ad did dismiss full screen content.")
  }
}

SwiftUI

fullScreenContentDelegate 屬性指派給傳回的廣告:

rewardedInterstitialAd?.fullScreenContentDelegate = self

實作通訊協定:

func adDidRecordImpression(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func adDidRecordClick(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func ad(
  _ ad: GADFullScreenPresentingAd,
  didFailToPresentFullScreenContentWithError error: Error
) {
  print("\(#function) called")
}

func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func adWillDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
  // Clear the rewarded interstitial ad.
  rewardedInterstitialAd = nil
}

Objective-C

@interface ViewController () <GADFullScreenContentDelegate>
@property(nonatomic, strong) GADRewardedInterstitialAd *rewardedInterstitialAd;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  [GADRewardedInterstitialAd
      loadWithAdUnitID:@"ca-app-pub-3940256099942544/6978759866"
                request:[GADRequest request]
      completionHandler:^(
          GADRewardedInterstitialAd *_Nullable rewardedInterstitialAd,
          NSError *_Nullable error) {
        if (!error) {
          self.rewardedInterstitialAd = rewardedInterstitialAd;
          self.rewardedInterstitialAd.fullScreenContentDelegate = self;
        }
      }];
}

/// Tells the delegate that the ad failed to present full screen content.
- (void)ad:(nonnull id<GADFullScreenPresentingAd>)ad
didFailToPresentFullScreenContentWithError:(nonnull NSError *)error {
    NSLog(@"Ad did fail to present full screen content.");
}

/// Tells the delegate that the ad will present full screen content.
- (void)adWillPresentFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {

    NSLog(@"Ad will present full screen content.");
}

/// Tells the delegate that the ad dismissed full screen content.
- (void)adDidDismissFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
  NSLog(@"Ad did dismiss full screen content.");
}

顯示廣告並處理獎勵事件

在呈現廣告時,您必須提供 GADUserDidEarnRewardHandler 物件,以便為使用者處理獎勵。

以下程式碼提供顯示獎勵插頁式廣告的最佳方法。

Swift

func show() {
  guard let rewardedInterstitialAd = rewardedInterstitialAd else {
    return print("Ad wasn't ready.")
  }

  // The UIViewController parameter is an optional.
  rewardedInterstitialAd.present(fromRootViewController: nil) {
    let reward = rewardedInterstitialAd.adReward
    print("Reward received with currency \(reward.amount), amount \(reward.amount.doubleValue)")
    // TODO: Reward the user.
  }
}

SwiftUI

監聽檢視畫面中的 UI 事件,以便顯示廣告。

var rewardedInterstitialBody: some View {
  // ...
  }
  .onChange(
    of: showAd,
    perform: { newValue in
      if newValue {
        viewModel.showAd()
      }
    }
  )

在檢視模型中顯示插頁式獎勵廣告:

func showAd() {
  guard let rewardedInterstitialAd = rewardedInterstitialAd else {
    return print("Ad wasn't ready.")
  }

  rewardedInterstitialAd.present(fromRootViewController: nil) {
    let reward = rewardedInterstitialAd.adReward
    print("Reward amount: \(reward.amount)")
    self.addCoins(reward.amount.intValue)
  }
}

Objective-C

- (void)show {
  // The UIViewController parameter is nullable.
  [_rewardedInterstitialAd presentFromRootViewController:nil
                                userDidEarnRewardHandler:^{

                                  GADAdReward *reward =
                                      self.rewardedInterstitialAd.adReward;
                                  // TODO: Reward the user.
                                }];
}

GitHub 上的範例

查看您偏好的語言的完整插頁式獎勵廣告範例:

後續步驟

進一步瞭解使用者隱私