Migración del SDK

En esta página, se describen las migraciones para las versiones actuales y anteriores del SDK de Google Mobile Ads para iOS. Se espera que la versión 11.0.0 se lance en enero de 2024.

Migra de la versión 10 a la 11 del SDK

部署目标下限

最低部署目标已提高至 iOS 12。

最低 Xcode 版本

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

广告停止在 iOS 12 设备上投放

Google 移动广告 SDK 版本 11.0.0 仅在搭载 iOS 13 及更高版本的设备上投放广告。

移除了 GoogleAppMeasurement 依赖项

在版本 11.0.0 中,移除了对 GoogleAppMeasurement 的依赖。这个为 AdMob 中用户指标切换开关提供支持的依赖项将于 2024 年初停用。如需继续在 AdMob 中收集用户指标,请将您的 AdMob 应用关联到 Firebase,并将 Google Analytics for Firebase SDK 集成到您的应用中。

全屏广告展示方式的变化

以下变更会影响各种广告格式:

  • 开屏广告
  • 插页式广告
  • 已奖励
  • 插页式激励广告

-canPresentFromRootViewController:error:-presentFromRootViewController: 中的视图控制器参数可为 null。如果传递 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 请改用 loadedAdNetworkResponseInfo 中的 adNetworkClassName

移除了 GADAdFormatUnknown

移除了 GADAdFormatUnknown,且无替代项。

日志记录 SDK 版本的更改

11.0.0 版移除了 sdkVersion。如需记录 Google 移动广告 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 界面中将设备明确声明为测试设备。

Migra de la versión 9 a la 10

广告停止在 iOS 11 设备上投放

Google 移动广告 SDK 版本 10.0.0 仅在搭载 iOS 12 及更高版本的设备上投放广告。

升级到 Google 移动广告 SDK 版本 10.0.0 不会影响您的应用在 iOS 11 和 iOS 10 设备上的行为,但广告不会在这些设备上投放。

不再支持使用位码构建

现在,您必须在移动应用中停用位码,才能集成 Google 移动广告 SDK。

已移除的类型

类型 备注
GADGender 无替代项。
GADMRewardBasedVideoAdNetworkAdapterProtocol 选择广告联盟一文中列出的所有激励广告中介适配器已停止使用这些协议超过一年了。将 GADMediationAdapter 用于中介和自定义事件。
GADMRewardBasedVideoAdNetworkConnectorProtocol

已移除的属性

以下属性已移除且无替代项。

v10.0.0 中的类 媒体资源
GADMediationAdRequest userBirthday
userGender
userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription
GADCustomEventRequest userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription

Cómo migrar de v8 a v9

Los anuncios dejan de publicarse en iOS 10

La versión mínima de iOS que admite la versión 9.0.0 del SDK de anuncios de Google para dispositivos móviles es iOS 11.

La actualización a la versión 9.0.0 del SDK de anuncios de Google para dispositivos móviles no causará fallas en tu app en los dispositivos con iOS 10; sin embargo, no se publicarán anuncios en esos dispositivos.

Aplicación más estricta de controles de la barra de estado

A partir de la versión 9.0.0, cuando presentas anuncios con formato de pantalla completa, tu app debe asegurarse de que los anuncios puedan controlar la presentación de la barra de estado. Si no lo haces, verás un mensaje de error en los registros.

Según el diseño específico de los controladores de vista de tu app, es posible que no necesites hacer ningún cambio para garantizar esto. Considera si necesitas establecer la propiedad childViewControllerForStatusBarHidden en el rootViewController de tu anuncio.

Se cambió el nombre de adDidPresentFullScreenContent: por adWillPresentFullScreenContent:

No se produce ningún cambio de comportamiento. El método delegado se invoca justo antes de que se muestre el anuncio, por lo que el nuevo nombre del método refleja mejor su funcionalidad.

Se quitó la API de configuración de ubicación en GADRequest

Se borró - (void)setLocationWithLatitude:longitude:accuracy: de GADRequest, ya que Google no usa los datos de ubicación para segmentar anuncios. Usa APIs de terceros para proporcionar la información a redes de publicidad de terceros si es necesario.

Baja de las interfaces de eventos personalizados

Los eventos personalizados permiten que los publicadores que usan AdMob Mediación agreguen la mediación en cascada para una red de publicidad que no es una de las redes de publicidad compatibles.

Todos los protocolos de eventos personalizados están obsoletos. En su lugar, usa los protocolos existentes GADMediationAdapter y GADMediationAdEventDelegate para lograr las mismas funciones. Este cambio mejora la claridad y te permite crear eventos personalizados para los anuncios recompensados y los anuncios interscroller que antes no estaban disponibles.

APIs

En la siguiente tabla, se enumeran las API de adaptador de mediación correspondientes a las API de eventos personalizados que se deben usar a partir de la versión 9.0.0.

v8 v9
GADCustomEventBanner
GADCustomEventIntersticial
GADCustomEventEvent
GADMediationAdapter GADMediationBannerAd
GADMediationInterstitialAd
GADMediationInterscrollerAd
GADMediationRewardedAd
GADMediationCodelab
delegate El controlador de finalización de carga de cada función de carga de la clase GADMediationAdapter muestra el delegado
-init -init
-requestBannerAd:parameter:label:request: -loadBannerForAdConfiguration:completionHandler:
-requestInterstitialAdWithParameter:label:request: -loadInterstitialForAdConfiguration:completionHandler:
-requestNativeAdWithParameter:request:adTypes:options:rootViewController: -loadNativeAdForAdConfiguration:completionHandler:
No disponible -loadInterscrollerAdForAdConfiguration:completionHandler:
No disponible -loadRewardedAdForAdConfiguration:completionHandler:
-presentFromRootViewController: -presentFromViewController:
-handlesUserClicks -handlesUserClicks
-handlesUserImpressions -handlesUserImpressions

Métodos delegados

En la siguiente tabla, se enumeran los métodos delegados de eventos de anuncios de mediación correspondientes para los métodos delegados de eventos personalizados que se deben usar a partir de la versión 9.0.0.

v8 v9
GADCustomEventBannerDelegate
GADCustomEventTimestampDelegate
GADCustomEventNearlineDelegate
GADMediationAdEventDelegate GADMediationAd
-customEventBanner:didReceiveAd:
-customEventInterstitialDidReceiveAd:
El estado de carga de anuncios se incluye en el controlador de finalización de carga de cada función de carga en la clase GADMediationAdapter.
-customEventBanner:didFailAd:
-customEventInterstitial:didFailAd:
-customEventBannerWasClicked:
-customEventInterstitialWasClicked:
-reportClick
-customEventBannerWillPresentModal:
-customEventInterstitialWillPresentModal:
-willPresentFullScreenView
-customEventBannerWillDismissModal:
-customEventInterstitialWillDismissModal:
-willDismissFullScreenView
-customEventBannerDidDismissModal:
-customEventInterstitialDidDismissModal:
-didDismissFullScreenView
-customEventBannerWillLeaveApplication:
-customEventInterstitialWillLeaveApplication:
-willBackgroundApplication
viewControllerForPresentingModalView -[GADMediationBannerAd view]

Otros métodos y constantes que se quitaron o reemplazaron

Cambios en el método, la constante o la propiedad
Constantes con prefijo kGAD- Se quitó el elemento. Usa constantes con prefijo GAD-.
GADAdNetworkResponseInfo Se quitaron credentials. En su lugar, usa adUnitMapping.
GAMRequest kGAMSimulatorID en GAMRequest dejó de estar disponible. En su lugar, usa GADSimulatorID en GADRequestConfiguration.
GADCustomNativeAd mediaView en GADCustomNativeAd dejó de estar disponible. Utiliza mediaContent en lugar de esta función.
APIs de In-App Purchase en GoogleMobileAds Se quitaron las APIs de inAppPurchase en GoogleMobileAds.

Migra de v7 a v8

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

展示广告并处理奖励

激励广告要求您在用户获得奖励时处理该事件。借助版本 7 的 GADRewardedAd API,您可以将 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 = 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.");
}

移除旧版 GADRewardedBasedVideoAd API

较新的 GADRewardedAd API 于 2019 年 3 月首次推出,在超过 18 个月的时间里一直是首选激励广告 API。与旧版 GADRewardedBasedVideoAd API 相比,新版 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 回调用作广告点击处理程序,如果依赖此回调来报告点击,将无法生成准确的指标。例如,用户点击“广告选择”图标时会启动外部浏览器,这时系统会调用该回调函数,但不会将其计为一次点击。

重命名类

下表列出了版本 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 中设置。
+disableAutomaticInAppPurchaseReporting -disableAutomaticInAppPurchaseReporting
+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 -initWithGMSID:
-setAdUnitID: -initWithGMSID:
adNetworkClassName responseInfo.adNetworkClassName
-interstitialWillLeaveApplication: 已移除
GADUnifiedNativeAd videoController mediaContent.videoController
adNetworkClassName responseInfo.adNetworkClassName