獎勵廣告

選取平台: Android iOS Unity Flutter

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

必要條件

一律使用測試廣告進行測試

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

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

ca-app-pub-3940256099942544/1712485313

這個 ID 經過特別設定,可針對每項要求傳回測試廣告,您可以在編寫、測試及偵錯時,自由地在自己的應用程式中使用。發布應用程式前,請務必將其替換為您自己的廣告單元 ID。

如要進一步瞭解 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

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;
              }];

註冊回呼

如要接收簡報事件的通知,請指派傳回廣告的 GADFullScreenContentDelegate to thefullScreenContentDelegate` 屬性:

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 回呼前取得獎勵金額,GADRewardedAd 具有 adReward 屬性,您可以在廣告載入後檢查該屬性,確認獎勵金額。
初始化呼叫是否會逾時?
10 秒後,Google Mobile Ads SDK 會叫用提供給 GADInitializationCompletionHandler startWithCompletionHandler: 方法的 ,即使中介服務聯播網尚未完成初始化也一樣。
如果我收到初始化回呼時,部分中介服務聯播網尚未準備就緒,該怎麼辦?

建議您在 GADInitializationCompletionHandler 內載入廣告。即使中介服務聯播網尚未準備就緒,Google Mobile Ads SDK 仍會向該聯播網要求廣告。因此,如果中介服務聯播網在逾時後完成初始化,仍可在該工作階段中處理日後的廣告請求。

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

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

GADAdapterStatus 物件的 description 屬性會說明介面卡無法處理廣告要求的原因。

userDidEarnRewardHandler 完成處理常式是否一律會在 adDidDismissFullScreenContent: 委派方法之前呼叫?

如果是 Google 廣告,所有 userDidEarnRewardHandler 呼叫都會在 adDidDismissFullScreenContent: 之前發生。如果是透過中介服務放送的廣告,回呼順序取決於第三方廣告聯播網 SDK 的實作方式。如果廣告聯播網 SDK 提供單一委派方法和獎勵資訊,中介服務轉接程式會先叫用 userDidEarnRewardHandler,再叫用 adDidDismissFullScreenContent:

GitHub 上的範例

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

後續步驟

進一步瞭解使用者隱私權