SDK 遷移

本頁說明 iOS 版 Google Mobile Ads SDK 目前及先前版本的遷移作業。11.0.0 版預計於 2024 年 1 月推出。

從 SDK 版本 v10 遷移至 v11

部署作業目標下限

最低部署目標已提高為 iOS 12。

最低 Xcode 版本

支援的最低 Xcode 版本已提高至 15.1。

iOS 12 上的廣告將停止放送

Google Mobile Ads SDK 11.0.0 版只會在搭載 iOS 13 以上版本的裝置上放送廣告。

已移除 GoogleAppMeasurement 依附元件

在 11.0.0 版中,已移除 GoogleAppMeasurement 的依附元件。這項依附元件在 AdMob 中支援使用者指標切換鈕,將於 2024 年初停用。如要繼續在 AdMob 中收集使用者指標,請將 AdMob 應用程式連結至 Firebase,並將 Google Analytics for Firebase SDK 整合至應用程式。

全螢幕廣告顯示方式異動

以下變更會影響各種廣告格式:

  • 應用程式開啟頁面廣告
  • 插頁式
  • 已獲得獎勵
  • 插頁式獎勵廣告

-canPresentFromRootViewController:error:-presentFromRootViewController: 中的檢視控制器參數可為空值。如果傳遞 nil,廣告就會顯示在檢視區塊控制器階層中最頂層的檢視控制器中。

移除的方法

下列方法已移除。

v11.0.0 類型 方法 附註
GADAppOpenAd load(withAdUnitID adUnitID: String, request: GADRequest?, orientation: UIInterfaceOrientation) 請改用 load(withAdUnitID adUnitID: String, request: GADRequest?)
GADMediationBannerAdEventDelegate willBackgroundApplication() 不得更換。
GADMediationInterstitialAdEventDelegate willBackgroundApplication() 不得更換。
GADMediationNativeAdEventDelegate willBackgroundApplication() 不得更換。
GADMediationRewardedAdEventDelegate didRewardUser(with reward: GADAdReward) 請改用 didRewardUser()
GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdWillLeaveApplication(_ mediatedNativeAd: GADMediatedUnifiedNativeAd) 不得更換。
GADRequestConfiguration setSameAppKeyEnabled(_ enabled: Bool) 請改用 setPublisherFirstPartyIDEnabled(_ enabled: Bool)
tagForUnderAge(ofConsent underAgeOfConsent: Bool) 請改用 tagForUnderAgeOfConsent 屬性。
tag(forChildDirectedTreatment childDirectedTreatment: Bool) 請改用 tagForChildDirectedTreatment 屬性。

已移除屬性

下列屬性已移除。

v11.0.0 類別 屬性 附註
GADMediationAdConfiguration hasUserLocation 不得更換。
userLatitude
userLongitude
userLocationAccuracyInMeters
childDirectedTreatment 請改用 GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment
GADResponseInfo adNetworkClassName 請改用 loadedAdNetworkResponseInfoadNetworkClassName

已移除 GADAdFormatUnknown

移除了 GADAdFormatUnknown,無法更換。

記錄 SDK 版本異動

11.0.0 版移除 sdkVersion。如要記錄 Google Mobile Ads SDK 版本,請改用 versionNumber

10.0.0 版

GADMobileAds.sharedInstance().sdkVersion

11.0.0 版

GADGetStringFromVersionNumber(GADMobileAds.sharedInstance().versionNumber)

GADAdLoader 錯誤處理變更

自 11.0.0 版起,如果 GADAdLoaderdelegate 不符合要求的廣告類型委派通訊協定,就不會發出廣告請求。先前則失敗。

測試行為異動

請參閱下表,瞭解下列屬性傳回 true 時的更新條件。

類別 屬性
GADMediationAdConfiguration isTestRequest
GADCustomEventRequest isTesting
v10.0.0 v11.0.0
  • 該裝置已在 testDeviceIdentifiers 中明確宣告為測試裝置。
  • 該裝置已在 testDeviceIdentifiers 中明確宣告為測試裝置。
  • 該裝置是模擬器。
  • 該裝置已在 AdMob UI 中明確宣告為測試裝置。

從 v9 遷移至 v10 版

廣告會在 iOS 11 上停止放送

Google Mobile Ads SDK 10.0.0 版只會在搭載 iOS 12 以上版本的裝置上放送廣告。

升級至 Google Mobile Ads SDK 10.0.0 版後,您的應用程式在 iOS 11 和 iOS 10 裝置上並不會受到影響,但將無法在這些裝置上放送。

不再支援使用中間碼進行建構

如要整合 Google Mobile Ads SDK,現在必須停用行動應用程式中的位元碼。

已移除的類型

類型 附註
GADGender 無法更換。
GADMRewardBasedVideoAdNetworkAdapterProtocol 選擇聯播網」中列出的所有獎勵中介服務轉接程式均已在一年內停止使用這些通訊協定。使用 GADMediationAdapter 處理中介服務和自訂事件。
GADMRewardBasedVideoAdNetworkConnectorProtocol

已移除資源

下列屬性已移除,且不會替換。

v10.0.0 類別 屬性
GADMediationAdRequest userBirthday
userGender
userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription
GADCustomEventRequest userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription

從第 8 版遷移至第 9 版

廣告會在 iOS 10 上停止放送

Google Mobile Ads SDK 9.0.0 版支援的 iOS 最低版本為 iOS 11。

升級至 Google Mobile Ads SDK 9.0.0 版後,您的應用程式在 iOS 10 裝置上並不會受到影響,但將無法在這些裝置上放送。

更嚴格的狀態列控制項強制執行措施

自 9.0.0 版起,在顯示全螢幕廣告格式時,應用程式應確保廣告能控制狀態列的呈現方式。如果沒有,記錄中會顯示錯誤訊息。

視應用程式中檢視區塊控制器的特定版面配置而定,您可能不需要進行任何變更來確保這一點。請考慮是否需要在廣告的 rootViewController 上設定 childViewControllerForStatusBarHidden 屬性。

將 adDidPresentFullScreenContent: 重新命名為 adWillPresentFullScreenContent:

系統的行為沒有改變。委派方法會在廣告即將顯示之前叫用,因此新方法名稱更能反映其功能。

移除 GADRequest 中的位置資訊設定 API

由於 Google 不會使用位置資料指定廣告目標,因此 - (void)setLocationWithLatitude:longitude:accuracy: 已從 GADRequest 中刪除。如有需要,請使用第三方 API 向第三方廣告聯播網提供資訊。

淘汰自訂事件介面

使用自訂事件,發布商可使用 AdMob 中介服務,為支援的廣告聯播網以外的廣告聯播網新增刊登序列中介服務。

所有自訂事件通訊協定已淘汰,請改用現有的 GADMediationAdapterGADMediationAdEventDelegate 通訊協定來達到相同功能。這項變更可使結果更清楚明瞭,並可讓您為獎勵廣告和 Interscroller 廣告建立自訂事件,但這之前無法使用。

API

下表列出應自 9.0.0 版起應使用的中介服務轉接程式 API,以及自訂事件 API。

v8 v9
GADCustomEvent 橫幅
GADCustomEvent 插頁式
GADCustomEventNativeAd
GADMediationAdapter GADMediationBannerAd
GADMediation 插頁式 Ad
GADMediationInterscrollerAd
GADMediation 獎勵廣告
GADMediationNativeAd
delegate GADMediationAdapter 類別中每個載入函式的載入完成處理常式會傳回委派
-init -init
-requestBannerAd:parameter:label:request: -loadBannerForAdConfiguration:completionHandler:
-requestInterstitialAdWithParameter:label:request: -loadInterstitialForAdConfiguration:completionHandler:
-requestNativeAdWithParameter:request:adTypes:options:rootViewController: -loadNativeAdForAdConfiguration:completionHandler:
不適用 -loadInterscrollerAdForAdConfiguration:completionHandler:
不適用 -loadRewardedAdForAdConfiguration:completionHandler:
-presentFromRootViewController: -presentFromViewController:
-handlesUserClicks -handlesUserClicks
-handlesUserImpressions -handlesUserImpressions

委派方法

下表列出從 9.0.0 版起應使用的自訂事件委派方法的對應中介服務廣告事件委派方法。

v8 v9
GADCustomEvent 橫幅委派
GADCustomEvent 插頁式委派
GADCustomEventNativeAd 委派
GADMediationAdEventDelegate GAD 中介服務廣告
-customEventBanner:didReceiveAd:
-customEventInterstitialDidReceiveAd:
廣告載入狀態包含在 GADMediationAdapter 類別內每個載入函式的載入完成處理常式中
-customEventBanner:didFailAd:
-customEventInterstitial:didFailAd:
-customEventBannerWasClicked:
-customEventInterstitialWasClicked:
-reportClick
-customEventBannerWillPresentModal:
-customEventInterstitialWillPresentModal:
-willPresentFullScreenView
-customEventBannerWillDismissModal:
-customEventInterstitialWillDismissModal:
-willDismissFullScreenView
-customEventBannerDidDismissModal:
-customEventInterstitialDidDismissModal:
-didDismissFullScreenView
-customEventBannerWillLeaveApplication:
-customEventInterstitialWillLeaveApplication:
-willBackgroundApplication
viewControllerForPresentingModalView -[GADMediationBannerAd view]

其他移除/取代的方法和常數

方法、常數或屬性變更
kGAD- 前置字元常數 已移除。使用 GAD- 前置字串常數。
GADAdNetworkResponseInfo 已移除 credentials。請改用 adUnitMapping
GAMRequest GAMRequest 中的 kGAMSimulatorID 已淘汰,請改用 GADRequestConfiguration 中的 GADSimulatorID
GADCustomNativeAd GADCustomNativeAd 中的 mediaView 已淘汰,請改用 mediaContent
GoogleMobileAds 中的應用程式內購 API 已移除 GoogleMobileAds 中的 inAppPurchase API。

從第 7 版遷移至第 8 版

Google Mobile Ads SDK 8.0.0 版推出了幾項重大變更,並重新命名及移除 API。

全螢幕格式 API 更新

從 8.0.0 版開始,插頁式廣告和獎勵廣告採用通用的全螢幕廣告樣式,進一步維持一致性。這些新的全螢幕廣告 API 與第 7 版全螢幕廣告 API 有兩大差異:

  1. 靜態類別方法 load

    上一次載入/顯示全螢幕廣告的方法:

    1. 建立廣告物件例項並保留其參照。
    2. 指派可處理載入並顯示回呼的委派項目。
    3. 載入廣告。
    4. 檢查廣告是否已使用 isReady 載入。
    5. 放送廣告。

    在第 8 版中,做法會稍有不同。載入回呼不再是委派的一部分。而是以完成處理常式的形式傳遞至 load 方法:

    1. 呼叫廣告類別上的靜態載入方法,並提供載入完成處理常式。
    2. 在載入完成回呼中,請保留系統傳回的已載入廣告參照。
    3. 指派可處理顯示回呼的委派。
    4. 放送廣告。

    新做法可帶來以下好處:

    • 您不會有任何未載入廣告的參照。
    • 廣告物件載入時,您不需要保留。
  2. 一致的廣告事件:

    事件類型 現有 API 第 8 版 API
    載入事件 GADInterstitialDelegateGADRewardedAdDelegate GADInterstitialAdLoadCompletionHandlerGADRewardedAdLoadCompletionHandler
    簡報事件 GADFullScreenContentDelegate

    以往,如要監聽任何廣告事件,您必須註冊將 GADInterstitialDelegate 通訊協定導入插頁式廣告委派屬性的類別,或是註冊將 GADRewardedAdDelegate 通訊協定導入獎勵廣告委派屬性的類別。該委派包含與廣告的載入和顯示生命週期相關的方法。

    使用第 8 版時,載入和簡報事件會分開。您現在可以在顯示廣告前隨時註冊 GADFullScreenContentDelegate,不需要在載入廣告前設定單一委派。各格式的廣告載入事件會移至載入方法傳入的單一載入完成處理常式。

插頁式

載入廣告

以下程式碼片段說明如何載入插頁式廣告,並在廣告成功或無法載入時監聽事件。

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADInterstitialDelegate {

  var interstitial: GADInterstitial!

  override func viewDidLoad() {
    super.viewDidLoad()
    interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/44118910")
    interstitial.delegate = self
    let request = GADRequest()
    interstitial.load(request)
  }

  /// Tells the delegate an ad request succeeded.
  func interstitialDidReceiveAd(_ ad: GADInterstitial) {
    print("Interstitial ad loaded.")
  }

  /// Tells the delegate an ad request failed.
  func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
    print("Interstitial ad failed to load with error: \(error.localizedDescription)")
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADInterstitial *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[GADInterstitial alloc]
      initWithAdUnitID:@"ca-app-pub-3940256099942544/44118910"];
  self.interstitial.delegate = self;
  GADRequest *request = [GADRequest request];
  [self.interstitial loadRequest:request];
}

/// Tells the delegate an ad request succeeded.
- (void)interstitialDidReceiveAd:(GADInterstitial *)ad {
  NSLog(@"Insterstitial ad loaded.");
}

/// Tells the delegate an ad request failed.
- (void)interstitial:(GADInterstitial *)ad
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@"Interstitial ad failed to load with error: %@", [error localizedDescription]);
}

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  var interstitial: GADInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    let request = GADRequest()
    GADInterstitialAd.load(withAdUnitID:"ca-app-pub-8123415297019784/4985798738",
                                request: request,
                      completionHandler: { (ad, error) in
                        if let error = error {
                          print("Failed to load interstitial ad with error: \(error.localizedDescription)")
                          return
                        }
                        self.interstitial = ad
                        self.interstitial.fullScreenContentDelegate = self
                      }
    )
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADInterstitialAd *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  GADRequest *request = [GADRequest request];
  [GADInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/44118910"
                              request:request
                    completionHandler:^(GADInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Failed to load interstitial ad with error: %@", [error localizedDescription]);
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

多媒體廣告

v7

Swift

func showInterstitial() {
  ...
  if interstitial.isReady {
    interstitial.present(fromRootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showInterstitial: {
  ...
  if (self.interstitial.isReady) {
    [self.interstitial presentFromRootViewController:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

v8

Swift

func showInterstitial() {
  ...
  if let ad = interstitial {
    ad.present(fromRootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showInterstitial: {
  ...
  if (self.interstitial) {
    [self.interstitial presentFromRootViewController:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

展示廣告事件

以下程式碼片段說明如何處理廣告顯示 (成功或失敗) 及關閉時的回呼。

v7

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/44118910")
  interstitial.delegate = self
  ...
}

/// Tells the delegate that an interstitial will be presented.
func interstitialWillPresentScreen(_ ad: GADInterstitial) {
  print("Interstitial ad will be presented.")
}

/// Tells the delegate the interstitial is to be animated off the screen.
func interstitialWillDismissScreen(_ ad: GADInterstitial) {
  print("Interstitial ad will be dismissed.")
}

/// Tells the delegate the interstitial had been animated off the screen.
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
  print("Interstitial ad dismissed.")
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
///
/// This is not a reliable callback for an ad click event and is removed in
/// version 8. If you wish to listen to an ad causing a user to leave the app,
/// use applicationWillResignActive: or sceneWillResignActive: instead.
func interstitialWillLeaveApplication(_ ad: GADInterstitial) {
  print("Interstitial ad will leave application.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:"ca-app-pub-3940256099942544/44118910"];
  self.interstitial.delegate = self;
  ...
}

/// Tells the delegate that an interstitial will be presented.
- (void)interstitialWillPresentScreen:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad will be presented.");
}

/// Tells the delegate the interstitial is to be animated off the screen.
- (void)interstitialWillDismissScreen:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad will be dismissed.");
}

/// Tells the delegate the interstitial had been animated off the screen.
- (void)interstitialDidDismissScreen:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad dismissed.");
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
///
/// This is not a reliable callback for an ad click event and is removed in
/// version 8. If you wish to listen to an ad causing a user to leave the app,
/// use applicationWillResignActive: or sceneWillResignActive: instead.
- (void)interstitialWillLeaveApplication:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad will leave application.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GADRequest()
  GADInterstitialAd.load(withAdUnitID:"ca-app-pub-8123415297019784/4985798738",
                              request: request,
                    completionHandler: { (ad, error) in
                      if let error = error {
                        print(error.localizedDescription)
                        return
                      }
                      self.interstitial = ad
                      self.interstitial.fullScreenContentDelegate = self
                    }
  )
}

func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Ad did present full screen content.")
}

func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
  print("Ad failed to present full screen content with error \(error.localizedDescription).")
}

func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Ad did dismiss full screen content.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  GADRequest *request = [GADRequest request];
  [GADInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/44118910"
                              request:request
                    completionHandler:^(GADInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"interstitial:didFailToReceiveAdWithError: %@", [error localizedDescription])
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

- (void)adDidPresentFullScreenContent:(id)ad {
  NSLog(@"Ad did present full screen content.");
}

- (void)ad:(id)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"Ad failed to present full screen content with error %@.", [error localizedDescription]);
}

- (void)adDidDismissFullScreenContent:(id)ad {
  NSLog(@"Ad did dismiss full screen content.");
}

已獲得獎勵

載入廣告

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADRewardedAdDelegate {
  /// The rewarded ad.
  var rewardedAd: GADRewardedAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
    rewardedAd.delegate = self
    rewardedAd?.load(GADRequest()) { error in
      if let error = error {
        print("Rewarded ad failed to load with error: \(error.localizedDescription)")
      } else {
        print("Rewarded ad loaded.")
      }
    }
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  self.rewardedAd = [[GADRewardedAd alloc]
      initWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"];
  self.rewardedAd.delegate = self;
  GADRequest *request = [GADRequest request];
  [self.rewardedAd loadRequest:request completionHandler:^(GADRequestError * _Nullable error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
    } else {
      NSLog(@"Rewarded ad loaded.");
    }
  }];
}

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {
  /// The rewarded ad.
  var rewardedAd: GADRewardedAd?

  override func viewDidLoad() {
  super.viewDidLoad()
  let request = GADRequest()
  GADRewardedAd.load(withAdUnitID: "ca-app-pub-8123415297019784/9501821136",
                          request: request, completionHandler: { (ad, error) in
                            if let error = error {
                              print("Rewarded ad failed to load with error: \(error.localizedDescription)")
                              return
                            }
                            self.rewardedAd = ad
                            self.rewardedAd?.fullScreenContentDelegate = self
                          }
  )
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  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.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

多媒體廣告與帳號代碼獎勵

您必須按照獎勵廣告領取使用者獲得獎勵時發生的事件。使用 GADRewardedAd 7 版 API 時,您可以在 GADRewardedAdDelegate 通訊協定中實作 rewardedAd:userDidEarnReward:。針對第 8 版,您必須導入 GADUserDidEarnRewardHandler 才能呈現廣告。

v7

Swift

func showRewardedAd() {
  ...
  if rewardedAd.isReady {
    rewardedAd.present(fromRootViewController: self delegate:self)
  } else {
    print("Ad wasn't ready")
  }
}

/// Tells the delegate that the user earned a reward.
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarnReward: GADAdReward) {
  // TODO: Reward the user.
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd.isReady) {
    [self.rewardedAd presentFromRootViewController:self delegate:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

/// Tells the delegate that the user earned a reward.
- (void)rewardedAd:(GADRewardedAd *)rewardedAd userDidEarnReward:(GADAdReward *)reward {
  // TODO: Reward the user.
}

v8

Swift

func showRewardedAd() {
  ...
  if let ad = rewardedAd {
      ad.present(fromRootViewController: self,
               userDidEarnRewardHandler: {
                 let reward = ad.adReward
                 // TODO: Reward the user.
               }
      )
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd) {
    [self.rewardedAd presentFromRootViewController:self
                          userDidEarnRewardHandler:^ {
      GADAdReward *reward = self.rewardedAd.adReward;
      // TODO: Reward the user.
    }];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

展示廣告事件

使用 GADRewardedAd API 時,您必須將 GADRewardedAdDelegate 傳遞至顯示廣告的方法。使用 GADRewardedAd API 時,您可以先將 GADFullscreenContentDelegate 設為廣告上的屬性,再顯示廣告。

v7

Swift

func showRewardedAd() {
  ...
  if rewardedAd.isReady {
    rewardedAd.present(fromRootViewController: self delegate:self)
  } else {
    print("Ad wasn't ready")
  }
}

/// Tells the delegate that the rewarded ad was presented.
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd.isReady) {
    [self.rewardedAd presentFromRootViewController:self delegate:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

/// Tells the delegate that the rewarded ad was presented.
- (void)rewardedAdDidPresent:(GADRewardedAd *)rewardedAd {
  NSLog(@"Rewarded ad presented.");
}

/// Tells the delegate that the rewarded ad failed to present.
- (void)rewardedAd:(GADRewardedAd *)rewardedAd didFailToPresentWithError:(NSError *)error {
  NSLog(@"Rewarded ad failed to present with error: %@",
        [error localizedDescription]);
}

/// Tells the delegate that the rewarded ad was dismissed.
- (void)rewardedAdDidDismiss:(GADRewardedAd *)rewardedAd {
  NSLog(@"Rewarded ad dismissed.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GADRequest()
  GADRewardedAd.load(withAdUnitID: "ca-app-pub-8123415297019784/9501821136",
                          request: request, completionHandler: { (ad, error) in
                            if let error = error {
                              print(error.localizedDescription)
                              return
                            }
                            self.rewardedAd = ad
                            self.rewardedAd?.fullScreenContentDelegate = self
                          }
  )
}

/// Tells the delegate that the rewarded ad was presented.
func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func ad(_ ad: GADFullScreenPresentingAd,
    didFailToPresentFullScreenContentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  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.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

/// Tells the delegate that the rewarded ad was presented.
- (void)adDidPresentFullScreenContent:(id)ad {
  NSLog(@"Rewarded ad presented.");
}

/// Tells the delegate that the rewarded ad failed to present.
- (void)ad:(id)ad
    didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"Rewarded ad failed to present with error: %@",
       [error localizedDescription]);
}

/// Tells the delegate that the rewarded ad was dismissed.
- (void)adDidDismissFullScreenContent:(id)ad {
  NSLog(@"Rewarded ad dismissed.");
}

移除舊版 GADPGBasedVideoAd API

新版 GADRewardedAd API 首次在 2019 年 3 月推出,已是 18 個月以上的首選獎勵 API。與舊版 GADRewardedBasedVideoAd API 相比,這個版本的強化功能更多,包括一次載入多個獎勵廣告。

舊版 GADRewardedBasedVideoAd API 已從 SDK 8.0.0 版中移除。

淘汰智慧型橫幅廣告,改用自動調整橫幅廣告

智慧型橫幅廣告已淘汰,並改用自動調整橫幅廣告。自動調整橫幅廣告能提供卓越成效,並靈活設定廣告寬度。如果您偏好繼續使用全寬度橫幅廣告,您仍可透過自動調整橫幅廣告完成這項操作,如以下程式碼片段所示:

Swift

class ViewController: UIViewController {

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // Note: The safe area is not known until viewWillAppear.
    let adSize = getFullWidthAdaptiveAdSize()
  }

  func getFullWidthAdaptiveAdSize() -> GADAdSize {
    // Here safe area is taken into account, hence the view frame is used after the
    // view has been laid out.
    let frame = { () -> CGRect in
      if #available(iOS 11.0, *) {
        return view.frame.inset(by: view.safeAreaInsets)
      } else {
        return view.frame
      }
    }()
    return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width)
  }
}

Objective-C

@implementation ViewController

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  // Note: The safe area is not known until viewWillAppear.
  GADAdSize adSize = [self getFullWidthAdaptiveAdSize];
}

- (GADAdSize)getFullWidthAdaptiveAdSize {
  CGRect frame = self.view.frame;
  // Here safe area is taken into account, hence the view frame is used after
  // the view has been laid out.
  if (@available(iOS 11.0, *)) {
    frame = UIEdgeInsetsInsetRect(self.view.frame, self.view.safeAreaInsets);
  }
  return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width);
}

@end

退出應用程式回呼

所有廣告格式的 willLeaveApplication 回呼都已移除,並改用 applicationDidEnterBackground:sceneDidEnterBackground: 方法。使用 OS 層級的 API 會在使用者離開應用程式時通知您,不論使用者是否因廣告互動而離開應用程式。

請注意, willLeaveApplication 回呼並非做為廣告點擊處理常式,而仰賴此回呼回報點擊並不會產生準確的指標。舉例來說,使用者在啟動外部瀏覽器叫用回呼的 AdChoices 圖示時,系統不會計算一次點擊。

重新命名課程

下表列出在第 8 版中已變更或移除的特定類別名稱。摘要說明:

  • GADUnifiedNativeAd 相關的所有類別已重新命名為 GADNativeAd
  • 已移除 GADRewardBasedVideoAdGADNativeExpressAdViewGADInstreamAd
  • 所有包含 DFP 前置字串的類別均已替換為 GAM 前置字串。
7.68.0 版類別 8.0.0 版類別
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial GAM 插頁式 Ad
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedNativeAd GADNativeAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNativeAd
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase 已移除
GADInterstitial GAD 插頁式 Ad
GADNativeExpressAdView 已移除
GADRewardBasedVideoAd 已移除
GADInstreamAd 已移除
GADInstreamAdView 已移除

移除/替換的方法

下表列出第 8 版的特定異動。摘要說明:

  • 已移除先前淘汰的方法和屬性。
  • 已移除所有格式的 -willLeaveApplication: 委派方法。
  • 廣告聯播網類別名稱已移至 GADResponseInfo 屬性。
  • 測試裝置 ID 已移至 GADRequestConfiguration 屬性。
7.68.0 版類別 7.68.0 版 API 8.0.0 版 API 附註
GADMobileAds +configureWithApplicationID: -startWithCompleteHandler: 應用程式 ID 現已在 Info.plist 中設定。
+disableAutomatedInAppPurchaseReporting -disableAutomatedInAppPurchaseReporting
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest testDevices GADRequestConfiguration.testdeviceidentifiers testDeviceIdentifiers 屬性適用於所有廣告請求,而舊的 testDevice 資源則是針對每個要求設定。
性別 已移除
生日 已移除
+sdkVersion GADMobileAds.sharedInstance.sdkVersion
-setBirthdayWithMonth:day:year: 已移除
-setLocationWithDescription: -setLocationWithLatitude:longitude:accuracy:
-tagForChildDirectedTreatment: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment]
GADErrorCode kGADError* GADError* 系統會從所有錯誤代碼常數中捨棄 k 前置字元。
GADBannerView hasAutoRefreshed autoloadEnabled
inAppPurchaseDelegate 已移除
mediatedAdView 已移除
adNetworkClassName responseInfo.adNetworkClassName
DFPBannerView -setValidAdSizesWithSizes: -setValidAdSizes:
DFPBannerViewOptions -adSizeApproval 已移除
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAdWithError: -bannerView:didFailToReceiveAdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: 已移除
GADNativeCustomTemplateAd templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey:customClickHandler: -performanceClickOnAssetWithKey:
GADNativeAdImageAdLoaderOptions preferredImageOrientation GADNativeAdMediaAdOptions.mediaAspectRatio
GADInterstitial inAppPurchaseDelegate 已移除
isReady 已移除 請改用 canPresentFromRootViewController:error:。
hasBeenUsed 已移除
-init -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
adNetworkClassName responseInfo.adNetworkClassName
-interstitialWillLeaveApplication: 已移除
GADUnifiedNativeAd videoController mediaContent.videoController
adNetworkClassName responseInfo.adNetworkClassName