Migración de SDK

En esta página, se describen las migraciones para las versiones actuales y anteriores.

Migra de v9 a v10

Los anuncios dejan de publicarse en iOS 11

La versión mínima de iOS 10.0.0 del SDK de los anuncios móviles de Google publica anuncios en iOS 12.

Si actualizas a la versión 10.0.0 del SDK de anuncios de Google para dispositivos móviles, tu app no fallará en dispositivos iOS 11 ni iOS 10; sin embargo, no se publicarán anuncios en ellos.

Ya no se admite la compilación con código de bits

Es necesario que inhabilites el código de bits en tus apps para dispositivos móviles a fin de integrar el SDK de Google Mobile Ads.

Tipos eliminados

Tipo Notas
Género GAD Sin reemplazo.
GADMRewardBasedVideoAdNetworkAdapterProtocol Todos los adaptadores de mediación recompensados que se enumeran en Elegir redes dejaron de usar estos protocolos durante más de un año. Usa GADMediationAdapter para eventos de mediación y personalizados.
GADMRewardVideoVideoNetworkNetworkConnectorProtocol

Se quitaron las propiedades

Las siguientes propiedades se quitan sin reemplazo.

Clase v10.0.0 Propiedad
Solicitud de mediación GAD usuariocumpleaños
userGender
usuarioHasLocation
Latitud del usuario
longitud del usuario
userLocationExactInInMeters
Descripción de la ubicación del usuario
GADCustomEventRequest usuarioHasLocation
Latitud del usuario
longitud del usuario
userLocationExactInInMeters
Descripción de la ubicación del usuario

Migra 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 los anuncios móviles de Google es iOS 11.

Si actualizas a la versión 9.0.0 del SDK de anuncios de Google para dispositivos móviles, tu app dejará de funcionar en dispositivos con iOS 10. Sin embargo, no se publicarán anuncios en ellos.

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

A partir de la versión 9.0.0, cuando presentas anuncios en 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 sea necesario realizar ningún cambio para garantizar esto. Considera si necesitas configurar la propiedad childViewControllerForStatusBarHidden en el rootViewController del anuncio.

Se cambió el nombre de adDidPresentFullScreenContent a adWillPresentFullScreenContent:

No hay cambios de comportamiento. El método delegado se invoca justo antes de que el anuncio esté por presentarse, por lo que el nombre del método nuevo refleja mejor su funcionalidad.

Quitar la API de configuración de la 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 las API de terceros para proporcionar la información a redes de publicidad de terceros si es necesario.

Las interfaces de eventos personalizados dejarán de estar disponibles

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

Todos los protocolos de eventos personalizados dejaron de estar disponibles. En su lugar, usa los protocolos existentes GADMediationAdapter y GADMediationAdEventDelegate para lograr las mismas funcionalidades. 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 del adaptador de mediación correspondientes a las API de eventos personalizados que deben usarse a partir de la versión 9.0.0.

v8 v9
GADCustomEventBanner
GADCustomEventInterstitial
GADCustomEventNativeAd
GADMediationAdapter GADMediationBannerAd
GADMediationInterstitialAd
GADMediationInterscrollerAd
GADMediationRewardedAd
GADMediationNativeAd
delegate El controlador de finalización de carga de cada función de carga de la clase GADMediationAdapter muestra Delegate.
-init -init
-requestBannerAd:parameter:label:request: -loadBannerForAdConfiguration:completionHandler:
-requestInterstitialAdWithParameter:label:request: -loadInterstitialForAdConfiguration:completionHandler:
-requestNativeAdWithParameter:request:adTypes:options:rootViewController: -loadNativeAdForAdConfiguration:completionHandler:
N/A -loadInterscrollerAdForAdConfiguration:completionHandler:
N/A -loadRewardedAdForAdConfiguration:completionHandler:
-presentFromRootViewController: -presentFromViewController:
-handlesUserClicks -handlesUserClicks
-handlesUserImpressions -handlesUserImpressions

Métodos de delegación

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

v8 v9
GADCustomEventBannerDelegate
GADCustomEventInterstitialDelegate
GADGADEventEventNativeAdDelegate
GADMediationAdEventDelegate Anuncio de GADMediation
-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
kGAD- constantes con prefijo Se quitó el elemento. Usa constantes con el 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.
API de compra directa desde la aplicación en GoogleMobileAds Se quitaron las API de inAppPurchase en GoogleMobileAds.

Migra de v7 a v8

La versión 8.0.0 del SDK de anuncios de Google para dispositivos móviles presenta algunos cambios importantes, así como algunos cambios de nombre y eliminaciones de API.

Actualizaciones de la API en formato de pantalla completa

A partir de la versión 8.0.0, los anuncios intersticiales y recompensados comparten un estilo genérico de anuncio de pantalla completa para brindar más coherencia. Estas nuevas API de anuncios de pantalla completa tienen dos distinciones principales de la versión 7:

  1. Método de clase estática load.

    El enfoque anterior para cargar o mostrar un anuncio de pantalla completa es el siguiente:

    1. Crea una instancia de objeto de anuncio y conserva una referencia a ella.
    2. Asigna un delegado que controle las cargas de llamada y muestre devoluciones de llamada.
    3. Carga un anuncio.
    4. Compruebe si el anuncio se carga con isReady.
    5. Muestre el anuncio.

    En la versión 8, el enfoque cambia ligeramente. Las devoluciones de llamada de carga ya no forman parte de un delegado. En su lugar, se pasan al método load como un controlador de finalización:

    1. Llama a un método de carga estática en la clase de anuncio y proporciona un controlador de finalización de carga.
    2. En la devolución de llamada de finalización de carga, conserva una referencia al anuncio cargado que se muestra.
    3. Asigna un delegado que controle las devoluciones de llamada del programa.
    4. Muestre el anuncio.

    El nuevo enfoque proporciona estos beneficios:

    • Nunca tendrá una referencia a un anuncio que no se cargue.
    • No es necesario que retenga un objeto de anuncio mientras se está cargando.
  2. Eventos de anuncio coherentes.

    Tipo de evento API existente API de v8
    Eventos de carga GADInterstitialDelegate o GADRewardedAdDelegate GADInterstitialAdLoadCompletionHandler o GADRewardedAdLoadCompletionHandler
    Eventos de presentación GADFullScreenContentDelegate

    Anteriormente, para escuchar eventos de anuncios, deberías registrar una clase que implemente el protocolo GADInterstitialDelegate en la propiedad de delegado de un anuncio intersticial o una clase que implemente el protocolo GADRewardedAdDelegate en la propiedad delegada de un anuncio recompensado, según el formato que uses. Este mismo delegado tenía métodos relacionados con el ciclo de vida de carga y presentación de un anuncio.

    En la versión 8, los eventos de carga y presentación son independientes. Ahora puedes registrar un GADFullScreenContentDelegate en cualquier momento antes de mostrar un anuncio en lugar de tener que establecer un solo delegado antes de cargarlo. Los eventos de carga de anuncios, que son específicos de cada formato, se mueven a un único controlador de finalización de carga que se pasa en el método de carga.

Intersticial

Cargar anuncio

En los siguientes fragmentos de código, se muestra cómo cargar un anuncio intersticial y detectar eventos cuando el anuncio se carga o no tiene éxito.

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

Anuncio gráfico

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

Eventos de anuncios de presentación

En los siguientes fragmentos de código, se muestra cómo controlar las devoluciones de llamada cuando el anuncio se presenta (de forma correcta o no) y cuando se descarta.

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.");
}

Recompensado

Cargar anuncio

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

Anuncio gráfico y administración de recompensas

Los anuncios recompensados requieren que usted maneje el evento cuando un usuario obtiene una recompensa. Con la versión 7 de la API de GADRewardedAd, implementa rewardedAd:userDidEarnReward: como parte del protocolo GADRewardedAdDelegate. En la versión 8, implementa GADUserDidEarnRewardHandler para presentar el anuncio.

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

Eventos de anuncios de presentación

Con la API de GADRewardedAd, pasas un GADRewardedAdDelegate al método que presenta el anuncio. Con la API de GADRewardedAd, configuras un objeto GADFullscreenContentDelegate como una propiedad en el anuncio antes de presentarlo.

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.");
}

Eliminación de la API heredada de GADRewardedBasedVideoAd

La API de GADRewardedAd más nueva se introdujo por primera vez en marzo de 2019 y ha sido la API recompensada preferida durante más de 18 meses. Tuvo más mejoras que la API heredada de GADRewardedBasedVideoAd, incluida la capacidad de cargar más de un anuncio recompensado a la vez.

Se quitó la API GADRewardedBasedVideoAd heredada en la versión 8.0.0 del SDK.

Baja del banner inteligente para priorizar el banner adaptable

Los anuncios de banners inteligentes dejaron de estar disponibles y se reemplazaron por los anuncios de banner adaptable. Los banners adaptables proporcionan un rendimiento superior y más flexibilidad en la configuración del ancho del anuncio. Si prefieres continuar usando banners de ancho completo, puedes hacerlo con un banner adaptable, como se muestra en el siguiente fragmento de código:

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

Cómo quitar la devolución de llamada de la aplicación

Se quitó la devolución de llamada willLeaveApplication de todos los formatos de anuncios y se reemplazó por los métodos applicationDidEnterBackground: y sceneDidEnterBackground:. El uso de API a nivel del SO te notificará cada vez que los usuarios abandonen tu app, independientemente de si se debe o no a una interacción con el anuncio.

Ten en cuenta que la devolución de llamada willLeaveApplication nunca estuvo destinada a ser un controlador de clics de anuncios y que depender de esta devolución de llamada para informar clics no produjo una métrica precisa. Por ejemplo, un clic en el ícono de AdChoices que iniciaba un navegador externo invocaba la devolución de llamada, pero no registraba un clic.

Cambio de nombre de clase

En la siguiente tabla, se enumeran los nombres de clases específicos que cambiaron o se quitaron en la versión 8. En resumen, haz lo siguiente:

  • Se cambió el nombre de todas las clases relacionadas con GADUnifiedNativeAd por GADNativeAd.
  • Se quitaron GADRewardBasedVideoAd, GADNativeExpressAdView y GADInstreamAd.
  • Se reemplazaron todas las clases con el prefijo DFP por un prefijo GAM.
Clase v7.68.0 Clase v8.0.0
Vista de banner de DFP Vista de banner de GAM
Opciones de vista del banner de DFP Opciones de vista del banner de GAM
Anuncio intersticial de DFP Anuncio de GAMInterstitial
Solicitud de DFP Solicitud de GAM
Error de solicitud GAD Error NS
UnifiedUnifiedViewView VistaDeADVa
GADUnifiedArgs. GADPubSub
GADUnifiedArgsAssetIdentifiers. GADWorkRequestAssetIdentifiers.
GADUnifiedTextViewDelegate GADFirstNameDelegate
GADUnifiedWorkRequestUnconfirmedClickDelegate GADFirstNameUnconfirmedClickDelegate
Anuncio de plantilla personalizado personalizado de GAD Personalizado en GAD
GADNativeCustomTemplateAdLoaderDelegate GADCustomWorkRequestLoaderDelegate
GADFirstNameDelegate GADCustomWorkRequestDelegate
GADInAppPurchase Quitado
GADIntersticial Anuncio intersticial para GAD
GADNativeExpressAdView Quitado
Anuncio de video basado en recompensas GAD Quitado
Anuncio GADInstream Quitado
GADInstreamAdView Quitado

Métodos que se quitaron o reemplazaron

En la siguiente tabla, se enumeran los cambios específicos de la versión 8. En resumen, haz lo siguiente:

  • Se quitaron los métodos y las propiedades que ya estaban obsoletos.
  • Se quitaron los métodos delegados -willLeaveApplication: para todos los formatos.
  • El nombre de la clase de la red de publicidad se movió a la propiedad GADResponseInfo.
  • El identificador de dispositivos de prueba se movió a la propiedad GADRequestConfiguration.
Clase v7.68.0 API de v7.68.0 API de v8.0.0 Notas
Anuncios para dispositivos móviles GAD +configureWithApplicationID: -startWithcompletionHandler: El ID de la app ahora está configurado en Info.plist.
+disableAutomatedInAppPurchaseReporting -disableAutomatedInAppPurchaseReporting
+disableSDKCrashReporting -disableSDKCrashReporting
Solicitud de GAD dispositivos de prueba GADRequestConfiguration.testdeviceidentifiers La propiedad testDeviceIdentifiers se aplica a todas las solicitudes de anuncios, mientras que la propiedad antigua TestDevices se estableció por solicitud.
género Quitado
cumpleaños Quitado
+sdkVersion GADMobileAds.sharedInstance.sdkVersion
-setBirthdayConmes:día:año: Quitado
-setLocationWithDescription: -setLocationWithLatitud:longitud:accuracy:
-tagForChildDirectedTreatment: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment]
Código de error GAD Error de kGAD* Error de GAD* El prefijo k se descarta de todas las constantes de código de error.
Vista de banner de GAD se actualizó automáticamente autoloadEnabled
inAppPurchaseDelegate Quitado
mediatedAdView Quitado
Nombre de clase de la red de anuncios responseInfo.adNetworkClassName
Vista de banner de DFP -setValidAdSizesWithSizes: -setValidAdSizes:
Opciones de vista del banner de DFP -adSizeDelegate Quitado
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAnuncio con error: -bannerView:didFailToReceiveAnuncio con error:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: Quitado
Anuncio de plantilla personalizado personalizado de GAD ID de plantilla GADCustomWorkRequest.formatID
-performClickOnAssetWithKey:customClickHandler: -performClickOnAssetWithKey:
Opciones de cargador de GADWorkRequestImageAd Orientación de imagen preferida GADTextViewMediaAdOptions.mediaAspectRatio
GADIntersticial inAppPurchaseDelegate Quitado
Está listo Quitado En su lugar, usa canPresentFromRootViewController:error.
Se usó Quitado
-init -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
Nombre de clase de la red de anuncios responseInfo.adNetworkClassName
- intersticialSalir de la aplicación: Quitado
GADUnifiedArgs. VideoControl mediaContent.videoController
Nombre de clase de la red de anuncios responseInfo.adNetworkClassName