獎勵廣告

選取平台: Android iOS Unity Flutter

使用者可選擇與獎勵廣告互動,換取應用程式內獎勵。本指南說明如何將 AdMob 獎勵廣告整合至 iOS 應用程式。 請參考客戶成功案例: 個案研究 1個案研究 2

必備條件

請務必使用測試廣告進行測試

建構及測試應用程式時,請務必使用測試廣告,而非實際運作中的廣告,否則可能導致帳戶遭停權。

載入測試廣告最簡單的方法,是使用 iOS 獎勵廣告專用的測試廣告單元 ID:

ca-app-pub-3940256099942544/1712485313

這種 ID 經特別設定,會針對每個請求傳回測試廣告。您可在編寫程式碼、測試及偵錯時,在自家應用程式中使用測試用 ID。但別忘了在發布應用程式前,將這類 ID 替換為自己的廣告單元 ID。

請參閱「測試廣告」,進一步瞭解 Google Mobile Ads SDK 測試廣告的運作方式。

導入方式

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

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

載入廣告

如要載入廣告,請使用 GADRewardedAd 類別的 load(adUnitID:request) 方法。

Swift

func loadRewardedAd() async {
  do {
    rewardedAd = try await RewardedAd.load(
      // Replace this ad unit ID with your own ad unit ID.
      with: "ca-app-pub-3940256099942544/1712485313", request: Request())
    rewardedAd?.fullScreenContentDelegate = self
  } catch {
    print("Rewarded ad failed to load with error: \(error.localizedDescription)")
  }
}

SwiftUI

import GoogleMobileAds

class RewardedViewModel: NSObject, ObservableObject, FullScreenContentDelegate {
  @Published var coins = 0
  private var rewardedAd: RewardedAd?

  func loadAd() async {
    do {
      rewardedAd = try await RewardedAd.load(
        with: "ca-app-pub-3940256099942544/1712485313", request: Request())
      rewardedAd?.fullScreenContentDelegate = self
    } catch {
      print("Failed to load rewarded ad with error: \(error.localizedDescription)")
    }
  }

Objective-C

// Replace this ad unit ID with your own ad unit ID.
[GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
              request:[GADRequest request]
    completionHandler:^(GADRewardedAd *ad, NSError *error) {
      if (error) {
        NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
        return;
      }
      self.rewardedAd = ad;
      self.rewardedAd.fullScreenContentDelegate = self;
    }];

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

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

請參考以下程式碼範例,瞭解如何在請求廣告前,設定獎勵廣告物件的自訂資料。

Swift

private func validateServerSideVerification() async {
  do {
    rewardedAd = try await RewardedAd.load(
      // Replace this ad unit ID with your own ad unit ID.
      with: "ca-app-pub-3940256099942544/1712485313", request: Request())
    let options = ServerSideVerificationOptions()
    options.customRewardText = "SAMPLE_CUSTOM_DATA_STRING"
    rewardedAd?.serverSideVerificationOptions = options
  } catch {
    print("Rewarded ad failed to load with error: \(error.localizedDescription)")
  }
}

Objective-C

// Replace this ad unit ID with your own ad unit ID.
[GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                        request:[GADRequest request]
              completionHandler:^(GADRewardedAd *ad, NSError *error) {
                if (error) {
                  NSLog(@"Rewarded ad failed to load with error: %@", error.localizedDescription);
                  return;
                }
                self.rewardedAd = ad;
                GADServerSideVerificationOptions *options =
                    [[GADServerSideVerificationOptions alloc] init];
                options.customRewardString = @"SAMPLE_CUSTOM_DATA_STRING";
                ad.serverSideVerificationOptions = options;
              }];

SAMPLE_CUSTOM_DATA_STRING 替換成自訂資料。

註冊回呼

為了接收廣告顯示事件的通知,請務必將 GADFullScreenContentDelegate 指派給傳回廣告的 fullScreenContentDelegate 屬性:

Swift

rewardedAd?.fullScreenContentDelegate = self

SwiftUI

rewardedAd?.fullScreenContentDelegate = self

Objective-C

self.rewardedAd.fullScreenContentDelegate = self;

GADFullScreenContentDelegate 通訊協定會處理下列情況中發生的回呼:廣告顯示成功/失敗,以及使用者關閉廣告。請查看下方程式碼,瞭解如何導入通訊協定:

Swift

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

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

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

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

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

func ad(
  _ ad: FullScreenPresentingAd,
  didFailToPresentFullScreenContentWithError error: Error
) {
  print("\(#function) called with error: \(error.localizedDescription).")
}

SwiftUI

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

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

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

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

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

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

Objective-C

- (void)adDidRecordImpression:(id<GADFullScreenPresentingAd>)ad {
  NSLog(@"%s called", __PRETTY_FUNCTION__);
}

- (void)adDidRecordClick:(id<GADFullScreenPresentingAd>)ad {
  NSLog(@"%s called", __PRETTY_FUNCTION__);
}

- (void)adWillPresentFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
  NSLog(@"%s called", __PRETTY_FUNCTION__);
}

- (void)adWillDismissFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
  NSLog(@"%s called", __PRETTY_FUNCTION__);
}

- (void)adDidDismissFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
  NSLog(@"%s called", __PRETTY_FUNCTION__);
  // Clear the rewarded ad.
  self.rewardedAd = nil;
}

- (void)ad:(id)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"%s called with error: %@", __PRETTY_FUNCTION__, error.localizedDescription);
}

顯示廣告並處理獎勵事件

顯示獎勵廣告前,請務必提供明確選項,讓使用者選擇是否觀看獎勵廣告素材來換取獎勵。使用者選擇觀看,獎勵廣告才會顯示。

顯示廣告時需提供 GADUserDidEarnRewardHandler 物件,用來處理給使用者的獎勵。

下列程式碼是顯示獎勵廣告的最佳方法:

Swift

rewardedAd.present(from: self) {
  let reward = rewardedAd.adReward
  print("Reward received with currency \(reward.amount), amount \(reward.amount.doubleValue)")

  // TODO: Reward the user.
}

SwiftUI

監聽檢視區塊中的 UI 事件,判斷廣告顯示時機。

var body: some View {
  VStack(spacing: 20) {
      Button("Watch video for additional 10 coins") {
        viewModel.showAd()
        showWatchVideoButton = false
      }

透過檢視區塊模型顯示獎勵廣告:

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

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

Objective-C

[self.rewardedAd presentFromRootViewController:self
                      userDidEarnRewardHandler:^{
                        GADAdReward *reward = self.rewardedAd.adReward;
                        NSString *rewardMessage = [NSString
                            stringWithFormat:@"Reward received with currency %@ , amount %lf",
                                             reward.type, [reward.amount doubleValue]];
                        NSLog(@"%@", rewardMessage);

                        // TODO: Reward the user.
                      }];

常見問題

可以查看 GADRewardedAd 的獎勵詳細資訊嗎?
可以。如要在觸發 userDidEarnReward 回呼前檢視獎勵數量,請在廣告載入後,檢查 GADRewardedAdadReward 屬性。
初始化呼叫有逾時限制嗎?
中介服務聯播網執行初始化 10 秒後,即使尚未完成,Google Mobile Ads SDK 仍會叫用提供給 startWithCompletionHandler: 方法的 GADInitializationCompletionHandler
收到初始化回呼時,如果部分中介服務聯播網尚未就緒,該怎麼辦?

建議在 GADInitializationCompletionHandler 中載入廣告。即使中介服務聯播網尚未就緒,Google Mobile Ads SDK 仍會請求廣告,因此,就算初始化程序是在逾時之後才完成,中介服務聯播網仍能處理該工作階段後續的廣告請求。

您可以在應用程式工作階段中持續呼叫 GADMobileAds.initializationStatus,輪詢所有轉接程式的初始化狀態。

如何找出特定中介服務聯播網尚未就緒的原因?

您可查看 GADAdapterStatus 物件的 description 屬性,瞭解轉接程式無法處理廣告請求的原因。

userDidEarnRewardHandler 完成處理常式收到呼叫的時機,一定是在 adDidDismissFullScreenContent: 委派方法之前嗎?

如果是 Google 廣告,userDidEarnRewardHandler 呼叫一定都發生在 adDidDismissFullScreenContent: 之前。若是透過中介服務放送的廣告,回呼順序取決於第三方廣告聯播網 SDK 的導入方式。若廣告聯播網 SDK 僅提供一個包含獎勵資訊的委派方法,中介服務轉接程式會先叫用 userDidEarnRewardHandler,再執行 adDidDismissFullScreenContent:

GitHub 上的範例

請選取您慣用的程式語言,查看完整的獎勵廣告範例:

後續步驟

進一步瞭解使用者隱私