SDK 遷移

本頁說明目前與先前版本的遷移作業。

從 10 遷移至 v11

部署作業目標下限

部署目標下限已提高為 iOS 12。

Xcode 最低版本

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

在 iOS 12 上停止放送廣告

Google Mobile Ads SDK 11.0.0 版只會在執行 iOS 13 的裝置上放送廣告 以及更高版本

已移除 GoogleAppMeasurement 依附元件

在 11.0.0 版中,依附元件 已為「GoogleAppMeasurement」 已移除只要採用這項依附元件,就能在 AdMob 中切換使用者指標 已停用。目的地: 繼續在 AdMob 中收集使用者指標 將 AdMob 應用程式連結至 Firebase,並 整合 Google Analytics for Firebase SDK

以全螢幕顯示廣告的方式異動

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

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

-canPresentFromRootViewController:error: 中的檢視控制器參數,以及 -presentFromRootViewController: 可為空值。如果傳遞 nil,廣告就會 從檢視區塊控制器階層中最上方的檢視控制器中產生

移除的方法

下列方法已移除。

11.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 屬性。

已移除屬性

下列屬性會一併移除。

11.0.0 版類別 屬性 附註
GADMediationAdConfiguration hasUserLocation 無法取代。
userLatitude
userLongitude
userLocationAccuracyInMeters
childDirectedTreatment 請改用 GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment
GADResponseInfo adNetworkClassName 請改用 loadedAdNetworkResponseInfo 中的 adNetworkClassName

已移除 GADAdFormat 不明

移除了 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 版起,如果 GADAdLoader 並未發出廣告請求 delegate 不符合請求的廣告類型委派通訊協定。先前 無法順利完成。

測試行為變更

請參閱下表,瞭解當下列項目的更新條件 則會傳回 true

類別 屬性
GADMediationAdConfiguration isTestRequest
GADCustomEventRequest isTesting
v10.0.0 v11.0.0
  • 已在 testDeviceIdentifiers 中明確宣告裝置為測試裝置。
  • 已在 testDeviceIdentifiers 中明確宣告裝置為測試裝置。
  • 該裝置是模擬器,
  • 而是在 Ad Manager 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 裝置上並不會受到影響,但將無法在這些裝置上放送。

Ad Manager 應用程式 ID 規定

現在,所有 Ad Manager 應用程式的 Info.plist 都需要 Ad Manager 應用程式 ID,且必須採用 ca-app-pub-################~########## 格式。詳情請參閱「更新您的 Info.plist」。

GoogleAppMeasurement.xcframework 需求

所有 Ad Manager 應用程式現在都必須使用 GoogleAppMeasurement.xcframework。如果您是透過 CocoapodsSwift Package Manager 安裝 Google Mobile Ads SDK,則無須採取其他行動。如果您手動安裝架構,請參閱手動下載一文瞭解詳細資訊。

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

如要整合 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

從 v8 遷移至 v9

廣告會在 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 向第三方廣告聯播網提供資訊。

淘汰自訂事件介面

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

所有自訂事件通訊協定已淘汰,請改用現有的 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 移动广告 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 v8 API
    加载事件 GADInterstitialDelegateGADRewardedAdDelegate GAMInterstitialAdLoadCompletionHandlerGADRewardedAdLoadCompletionHandler
    展示事件 GADFullScreenContentDelegate

    以前,要监听任何广告事件,您需要注册一个 实现了 GADInterstitialDelegate 协议传递给插页式广告的委托属性,或者注册一个 实现了 GADRewardedAdDelegate 协议传递给激励广告的委托属性,具体取决于 资源。此代理包含与加载和 广告的呈现生命周期。

    在版本 8 中,加载事件和展示事件是分开的。现在,您可以 注册 GADFullScreenContentDelegate 而无需设置单个 代理。广告加载事件(特定于每个 格式,移至加载方法中传递的单个加载完成处理程序。

插页式广告

加载广告

以下代码段展示了如何加载插页式广告并监听 事件。

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADInterstitialDelegate {

  var interstitial: DFPInterstitial!

  override func viewDidLoad() {
    super.viewDidLoad()
    interstitial = DFPInterstitial(adUnitID: "/21775744923/example/interstitial")
    interstitial.delegate = self
    let request = GAMRequest()
    interstitial.load(request)
  }

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

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

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) DFPInterstitial *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[DFPInterstitial alloc]
      initWithAdUnitID:@"/21775744923/example/interstitial"];
  self.interstitial.delegate = self;
  GAMRequest *request = [GAMRequest request];
  [self.interstitial loadRequest:request];
}

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

/// Tells the delegate an ad request failed.
- (void)interstitial:(DFPInterstitial *)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: GAMInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    let request = GAMRequest()
    GAMInterstitialAd.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) GAMInterstitialAd *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  GAMRequest *request = [GAMRequest request];
  [GAMInterstitialAd loadWithAdUnitID:@"/21775744923/example/interstitial"
                              request:request
                    completionHandler:^(GAMInterstitialAd *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 = DFPInterstitial(adUnitID: "/21775744923/example/interstitial")
  interstitial.delegate = self
  ...
}

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

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

/// Tells the delegate the interstitial had been animated off the screen.
func interstitialDidDismissScreen(_ ad: DFPInterstitial) {
  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: DFPInterstitial) {
  print("Interstitial ad will leave application.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[DFPInterstitial alloc] initWithAdUnitID:"/21775744923/example/interstitial"];
  self.interstitial.delegate = self;
  ...
}

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

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

/// Tells the delegate the interstitial had been animated off the screen.
- (void)interstitialDidDismissScreen:(DFPInterstitial *)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:(DFPInterstitial *)ad {
  NSLog(@"Interstitial ad will leave application.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GAMRequest()
  GAMInterstitialAd.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];
  GAMRequest *request = [GAMRequest request];
  [GAMInterstitialAd loadWithAdUnitID:@"/21775744923/example/interstitial"
                              request:request
                    completionHandler:^(GAMInterstitialAd *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(GAMRequest()) { 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;
  GAMRequest *request = [GAMRequest 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 = GAMRequest()
  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];

  GAMRequest *request = [GAMRequest 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 API 的版本 7 时,您需要实现 rewardedAd:userDidEarnReward:(作为 GADRewardedAdDelegate 协议的一部分)。 对于版本 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 = GAMRequest()
  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];

  GAMRequest *request = [GAMRequest 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.");
}

移除旧版 GADRewardedBasedVideoAd API

较新的 GADRewardedAd API 于 2019 年 3 月首次推出,已成为 API 使用超过 18 个月。与旧版相比,新版 SDK 具备更多增强功能 GADRewardedBasedVideoAd API,其中包括加载多个 每次观看激励广告

SDK 版本 8.0.0 中移除了旧版 GADRewardedBasedVideoAd API。

弃用智能横幅广告,取而代之的是自适应横幅广告

智能横幅广告已被弃用 弃用自适应横幅广告 广告。自适应横幅广告可提供卓越的效果和更大的灵活性, 设置广告宽度。如果您希望继续使用全宽横幅广告 仍使用自适应横幅广告,如以下代码段所示:

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: 方法。如果使用操作系统级 API,无论用户何时离开您的应用,无论他们是什么原因,您都会收到通知 是否属于广告互动

请注意, willLeaveApplication 回调的设计初衷 广告点击处理程序,而依靠此回调来报告点击次数 都会得出准确的指标例如,点击“广告选项” 图标表示已启动外部浏览器调用了回调,但是未计入 点击。

重命名类

下表列出了在 2 中已更改或移除的具体类名称 版本 8。总结:

  • GADUnifiedNativeAd 相关的所有类均已重命名为 GADNativeAd
  • GADRewardBasedVideoAdGADNativeExpressAdViewGADInstreamAd 已移除。
  • 所有带 DFP 前缀的类均已替换为 GAM 前缀。
v7.68.0 中的类 v8.0.0 中的类
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial GAMInterstitialAd
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedNativeAd GADNativeAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNativeAd
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase 已移除
GADInterstitial GADInterstitialAd
GADNativeExpressAdView 已移除
GADRewardBasedVideoAd 已移除
GADInstreamAd 已移除
GADInstreamAdView 已移除

移除/替换的方法

下表列出了版本 8 中的具体更改。总结:

  • 移除了之前已废弃的方法和属性。
  • 移除了所有格式的 -willLeaveApplication: 委托方法。
  • 广告联盟类名称已移至 GADResponseInfo 属性。
  • 测试设备标识符已移至 GADRequestConfiguration 属性。
v7.68.0 中的类 v7.68.0 中的 API v8.0.0 中的 API 备注
GADMobileAds +configureWithApplicationID: -startWithCompletionHandler: 现在,应用 ID 已在 Info.plist 中设置。
+disableAutomatedInAppPurchaseReporting -disableAutomatedInAppPurchaseReporting
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest testDevices GADRequestConfiguration.testdeviceidentifiers testDeviceIdentifiers 属性适用于所有广告请求,而 旧版 testDevices 属性是按请求设置的。
性别 已移除
生日 已移除
+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 -adSizeDelegate 已移除
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAdWithError: -bannerView:didFailToReceiveAdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: 已移除
GADNativeCustomTemplateAd templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey:customClickHandler: -performClickOnAssetWithKey:
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