使用者可選擇與獎勵廣告互動,藉此換取應用程式內獎勵。本指南將說明如何將 AdMob 的獎勵廣告整合至 iOS 應用程式。 閱讀一些客戶成功案例:個案研究 1、個案研究 2。
必要條件
- Google Mobile Ads SDK 8.0.0 以上版本。
- 完成入門指南。
請務必使用測試廣告進行測試
建構及測試應用程式時,請務必使用測試廣告,而非實際的正式版廣告。否則可能導致帳戶遭到停權。
如要載入測試廣告,最簡單的方法是使用 iOS 獎勵廣告專用的測試廣告單元 ID:
ca-app-pub-3940256099942544/1712485313
這項廣告單元已特別設定為針對每項要求傳回測試廣告,您可以在編寫程式碼、測試及偵錯時,在自己的應用程式中自由使用這項廣告單元。只要在發布應用程式前,將其替換為自己的廣告單元 ID 即可。
如要進一步瞭解 Mobile Ads SDK 的測試廣告運作方式,請參閱「測試廣告」。
實作
整合獎勵廣告的主要步驟如下:
- 載入廣告
- [選用] 驗證 SSV 回呼
- 註冊回呼
- 顯示廣告並處理獎勵事件
載入廣告
您可以使用 GADRewardedAd
類別的 load(adUnitID:request)
方法載入廣告。
Swift
import GoogleMobileAds
import UIKit
class ViewController: UIViewController {
private var rewardedAd: GADRewardedAd?
func loadRewardedAd() async {
do {
rewardedAd = try await GADRewardedAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/1712485313", request: GADRequest())
} catch {
print("Rewarded ad failed to load with error: \(error.localizedDescription)")
}
}
}
SwiftUI
import GoogleMobileAds
class RewardedViewModel: NSObject, ObservableObject, GADFullScreenContentDelegate {
@Published var coins = 0
private var rewardedAd: GADRewardedAd?
func loadAd() async {
do {
rewardedAd = try await GADRewardedAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/1712485313", request: GADRequest())
rewardedAd?.fullScreenContentDelegate = self
} catch {
print("Failed to load rewarded ad with error: \(error.localizedDescription)")
}
}
Objective-C
@import GoogleMobileAds;
@import UIKit;
@interface ViewController ()
@property(nonatomic, strong) GADRewardedAd *rewardedAd;
@end
@implementation ViewController
- (void)loadRewardedAd {
GADRequest *request = [GADRequest request];
[GADRewardedAd
loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
request:request
completionHandler:^(GADRewardedAd *ad, NSError *error) {
if (error) {
NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
return;
}
self.rewardedAd = ad;
NSLog(@"Rewarded ad loaded.");
}];
}
[選用] 驗證伺服器端驗證 (SSV) 回呼
如果應用程式需要在伺服器端驗證回呼中使用額外資料,則應使用獎勵廣告的客製資料功能。獎勵廣告物件上設定的任何字串值,都會傳遞至 SSV 回呼的 custom_data
查詢參數。如果未設定自訂資料值,SSV 回呼中就不會顯示 custom_data
查詢參數值。
以下程式碼範例示範如何在要求廣告前,在獎勵廣告物件上設定自訂資料。
Swift
do {
rewardedAd = try await GADRewardedAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/1712485313", request: GADRequest())
let options = GADServerSideVerificationOptions()
options.customRewardString = "SAMPLE_CUSTOM_DATA_STRING"
rewardedAd.serverSideVerificationOptions = options
} catch {
print("Rewarded ad failed to load with error: \(error.localizedDescription)")
}
Objective-C
[GADRewardedAd
loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
request:[GADRequest request];
completionHandler:^(GADRewardedAd *ad, NSError *error) {
if (error) {
// Handle Error
return;
}
self.rewardedAd = 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 rewardedAd: GADRewardedAd?
func loadRewardedAd() async {
do {
rewardedAd = try await GADRewardedAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/1712485313", request: GADRequest())
rewardedAd?.fullScreenContentDelegate = self
} catch {
print("Rewarded ad failed to load 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
屬性指派給傳回的廣告:
rewardedAd?.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 ad.
rewardedAd = nil
}
Objective-C
@interface ViewController () <GADFullScreenContentDelegate>
@property(nonatomic, strong) GADRewardedAd *rewardedAd;
@end
@implementation ViewController
- (void)loadRewardedAd {
GADRequest *request = [GADRequest request];
[GADRewardedAd
loadWithAdUnitID:@"ca-app-pub-3940256099942544/4806952744"
request:request
completionHandler:^(GADRewardedAd *ad, NSError *error) {
if (error) {
NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
return;
}
self.rewardedAd = ad;
NSLog(@"Rewarded ad loaded.");
self.rewardedAd.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.");
}
GADRewardedAd
是一次性物件。也就是說,獎勵廣告一經顯示,就無法再顯示。最佳做法是在 GADFullScreenContentDelegate
的 adDidDismissFullScreenContent:
方法中載入另一則獎勵廣告,這樣一來,系統就能在先前廣告關閉後立即開始載入下一個獎勵廣告。
顯示廣告並處理獎勵事件
向使用者顯示獎勵廣告前,請務必向使用者顯示明確的選項,讓他們可以選擇觀看獎勵廣告內容以換取獎勵。獎勵廣告一律必須是選擇加入的體驗。
在呈現廣告時,您必須提供 GADUserDidEarnRewardHandler
物件,以便為使用者處理獎勵。
以下程式碼提供顯示獎勵廣告的最佳方法。
Swift
func show() {
guard let rewardedAd = rewardedAd else {
return print("Ad wasn't ready.")
}
// The UIViewController parameter is an optional.
ad.present(fromRootViewController: nil) {
let reward = ad.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(fromRootViewController: nil) {
let reward = rewardedAd.adReward
print("Reward amount: \(reward.amount)")
self.addCoins(reward.amount.intValue)
}
}
Objective-C
- (void)show {
if (self.rewardedAd) {
// The UIViewController parameter is nullable.
[self.rewardedAd presentFromRootViewController:nil
userDidEarnRewardHandler:^{
GADAdReward *reward =
self.rewardedAd.adReward;
// TODO: Reward the user!
}];
} else {
NSLog(@"Ad wasn't ready");
}
}
常見問題
- 可以提供
GADRewardedAd
的獎勵詳細資料嗎? - 是的,如果您需要在
userDidEarnReward
回呼觸發前取得獎勵金額,GADRewardedAd
就會提供adReward
屬性,方便您在廣告載入後驗證獎勵金額。 - 初始化呼叫是否有逾時限制?
- 10 秒後,即使中介服務聯播網仍未完成初始化,Google Mobile Ads SDK 也會叫用提供給
startWithCompletionHandler:
方法的GADInitializationCompletionHandler
。 - 如果在收到初始化回呼時,部分中介服務聯播網尚未就緒,該怎麼辦?
建議您在
GADInitializationCompletionHandler
中載入廣告。即使中介服務聯播網尚未就緒,Google Mobile Ads SDK 仍會向該聯播網要求廣告。因此,如果中介服務網路在逾時後完成初始化,仍可在該工作階段中處理未來的廣告請求。您可以呼叫
GADMobileAds.initializationStatus
,繼續在應用程式工作階段中輪詢所有轉接程式的初始化狀態。- 如何找出特定中介服務聯播網未就緒的原因?
GADAdapterStatus
物件的description
屬性會說明為何轉接程式無法處理廣告請求。userDidEarnRewardHandler
完成處理常式是否一律會在adDidDismissFullScreenContent:
委派方法之前呼叫?對於 Google 廣告,所有
userDidEarnRewardHandler
呼叫都會在adDidDismissFullScreenContent:
之前發生。對於透過中介服務放送的廣告,第三方廣告聯播網 SDK 的導入方式會決定回呼順序。如果廣告聯播網 SDK 提供單一委派方法,且含有獎勵資訊,中介服務轉接程式會在adDidDismissFullScreenContent:
之前叫用userDidEarnRewardHandler
。
GitHub 上的範例
查看您偏好的語言的完整獎勵廣告範例:
後續步驟
進一步瞭解使用者隱私權。