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

Objetivo de implementación mínimo

El objetivo de implementación mínimo aumentó a iOS 12.

Versión mínima de Xcode

La versión mínima de Xcode compatible se aumentó a 15.1.

Los anuncios dejarán de publicarse en iOS 12

La versión 11.0.0 del SDK de anuncios de Google para dispositivos móviles publica anuncios solo en dispositivos con iOS 13 y versiones posteriores.

Se quitó la dependencia GoogleAppMeasurement.

En la versión 11.0.0, se quitó la dependencia de GoogleAppMeasurement. Esta dependencia que activó el botón de activación de las métricas del usuario en AdMob se discontinuará a principios de 2024. Para seguir recopilando métricas del usuario en AdMob, vincula tu app de AdMob a Firebase y, luego, integra el SDK de Google Analytics para Firebase a la app.

Cambios en la presentación de anuncios en pantalla completa

Los siguientes cambios afectan los distintos formatos de anuncio:

  • Inicio de aplicación
  • Intersticial
  • Recompensado
  • Anuncio intersticial recompensado

El parámetro del controlador de vista en -canPresentFromRootViewController:error: y -presentFromRootViewController: es anulable. Si se pasa un valor nulo, el anuncio se presenta desde el controlador de vista superior en la jerarquía del controlador de vista.

Se quitaron métodos

Se quitaron los siguientes métodos.

Tipo v11.0.0 Método Notas
GADAppOpenAd load(withAdUnitID adUnitID: String, request: GADRequest?, orientation: UIInterfaceOrientation) En su lugar, usa load(withAdUnitID adUnitID: String, request: GADRequest?).
GADMediationBannerAdEventDelegate willBackgroundApplication() Sin reemplazo.
GADMediationInterstitialAdEventDelegate willBackgroundApplication() Sin reemplazo.
GADMediationNativeAdEventDelegate willBackgroundApplication() Sin reemplazo.
GADMediationRewardedAdEventDelegate didRewardUser(with reward: GADAdReward) En su lugar, usa didRewardUser().
GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdWillLeaveApplication(_ mediatedNativeAd: GADMediatedUnifiedNativeAd) Sin reemplazo.
GADRequestConfiguration setSameAppKeyEnabled(_ enabled: Bool) Usa setPublisherFirstPartyIDEnabled(_ enabled: Bool) en su lugar.
tagForUnderAge(ofConsent underAgeOfConsent: Bool) En su lugar, usa la propiedad tagForUnderAgeOfConsent.
tag(forChildDirectedTreatment childDirectedTreatment: Bool) En su lugar, usa la propiedad tagForChildDirectedTreatment.

Se quitaron las propiedades

Se quitaron las siguientes propiedades.

Clase v11.0.0 Propiedad Notas
GADMediationAdConfiguration hasUserLocation Sin reemplazo.
userLatitude
userLongitude
userLocationAccuracyInMeters
childDirectedTreatment En su lugar, usa GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment.
GADResponseInfo adNetworkClassName En su lugar, usa adNetworkClassName de loadedAdNetworkResponseInfo.

Se quitó GADAdFormatUnknown.

Se quitó GADAdFormatUnknown sin reemplazo.

Cambios en la versión de registro del SDK

La versión 11.0.0 quita sdkVersion. Para registrar la versión del SDK de anuncios de Google para dispositivos móviles, usa versionNumber en su lugar.

Versión 10.0.0

GADMobileAds.sharedInstance().sdkVersion

Versión 11.0.0

GADGetStringFromVersionNumber(GADMobileAds.sharedInstance().versionNumber)

Cambios en el manejo de errores de GADAdLoader

A partir de la versión 11.0.0, GADAdLoader no realizará una solicitud de anuncio si su delegate no cumple con el protocolo de delegado de tipos de anuncios solicitado. Anteriormente, fallaba después de que se realizaba la solicitud de anuncio.

Cambios en el comportamiento de las pruebas

Consulta la tabla en la que se muestran las condiciones actualizadas cuando las siguientes propiedades muestran true.

Clase Propiedad
GADMediationAdConfiguration isTestRequest
GADCustomEventRequest isTesting
v10.0.0 v11.0.0
  • El dispositivo se declara explícitamente como dispositivo de prueba en testDeviceIdentifiers.
  • El dispositivo se declara explícitamente como dispositivo de prueba en testDeviceIdentifiers.
  • El dispositivo es un simulador.
  • El dispositivo se declara explícitamente como dispositivo de prueba en la IU de AdMob .

Migra de la versión 9 a la 10

Los anuncios dejan de publicarse en iOS 11

La versión 10.0.0 del SDK de anuncios de Google para dispositivos móviles publica anuncios solo en dispositivos con iOS 12 y versiones posteriores.

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

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

Ahora es necesario inhabilitar el código de bits en tus apps para dispositivos móviles para integrar el SDK de anuncios de Google para dispositivos móviles.

Tipos quitados

Tipo Notas
GADGender Sin reemplazo.
GADMRewardBasedVideoAdNetworkAdapterProtocol Todos los adaptadores de mediación para premios que figuran en Elegir redes dejaron de usar estos protocolos durante más de un año. Usa GADMediationAdapter para la mediación y eventos personalizados.
GADMRewardBasedVideoAdNetworkConnectorProtocol

Se quitaron las propiedades

Las siguientes propiedades se quitan sin reemplazo.

Clase v10.0.0 Propiedad
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

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

Actualizaciones de la API de formato de pantalla completa

A partir de la versión 8.0.0, los anuncios intersticiales y recompensados comparten un estilo de anuncio de pantalla completa genérico para lograr una mayor coherencia. Estas nuevas APIs de anuncios de pantalla completa tienen dos diferencias importantes de las APIs de anuncios de pantalla completa 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 la carga y muestre las devoluciones de llamada.
    3. Carga un anuncio.
    4. Verifica si el anuncio se cargó con isReady.
    5. Muestra el anuncio.

    En la versión 8, el enfoque cambia un poco. 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ático 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 la carga, mantén una referencia al anuncio cargado que se muestra.
    3. Asigna un delegado que controle las devoluciones de llamada de muestra.
    4. Muestra el anuncio.

    El nuevo enfoque proporciona los siguientes beneficios:

    • Nunca verás una referencia a un anuncio que no se haya cargado.
    • No es necesario que retengas un objeto de anuncio mientras se carga.
  2. Eventos de anuncios coherentes.

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

    Anteriormente, para escuchar cualquier evento de anuncios, se registraba una clase que implementaba el protocolo GADInterstitialDelegate en la propiedad de delegado de un anuncio intersticial o registrabas una clase que implementa el protocolo GADRewardedAdDelegate en la propiedad de delegado 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.

    Con 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 configurar un solo delegado antes de cargar el anuncio. Los eventos de carga de anuncios, que son específicos para cada formato, se trasladan a un solo 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 correctamente o no.

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 para cuando el anuncio se presenta (de forma correcta o sin éxito) 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 identificador de la recompensa

Los anuncios recompensados requieren que controles el evento cuando un usuario obtiene una recompensa. Con la versión 7 de la API de GADRewardedAd, implementas rewardedAd:userDidEarnReward: como parte del protocolo GADRewardedAdDelegate. En la versión 8, debes implementar 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, puedes configurar un objeto GADFullscreenContentDelegate como propiedad del 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 de GADRewardedBasedVideoAd heredada

La API de GADRewardedAd más reciente se introdujo por primera vez en marzo de 2019 y ha sido la API recompensada preferida por más de 18 meses. Tiene más mejoras en comparación con la API de GADRewardedBasedVideoAd heredada, incluida la capacidad de cargar más de un anuncio recompensado a la vez.

La API de GADRewardedBasedVideoAd heredada se quita en la versión 8.0.0 del SDK.

Baja de los banners inteligentes para dar lugar a los banners adaptables

Los banners inteligentes dejaron de estar disponibles y se reemplazaron por los anuncios de banners adaptables. Los banners adaptables proporcionan un rendimiento superior y más flexibilidad a la hora de configurar el ancho del anuncio. Si prefieres seguir usando los banners de ancho completo, puedes hacerlo con los banners adaptables, 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

Salir de la eliminación de la devolución de llamada de la aplicación

Se quitó la devolución de llamada willLeaveApplication para todos los formatos de anuncios y se reemplazó por los métodos applicationDidEnterBackground: y sceneDidEnterBackground:. Las APIs a nivel del SO te notifican cuando los usuarios abandonan tu app, sin importar si se debe a una interacción con el anuncio o no.

Ten en cuenta que la devolución de llamada willLeaveApplication nunca estuvo diseñada para ser un controlador de clics en el anuncio, y utilizar esta devolución de llamada para informar clics no produjo una métrica precisa. Por ejemplo, un clic en el ícono de AdChoices que inició un navegador externo invocó la devolución de llamada, pero no registró un clic.

Cambio de nombre de la clase

En la siguiente tabla, se enumeran los nombres de clases específicos que se modificaron 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.
  • Todas las clases con el prefijo DFP se reemplazaron por un prefijo GAM.
Clase v7.68.0 Clase v8.0.0
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial Anuncio intersticial de GAM
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedContainer GADDescubrimiento
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNearline
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase Quitada
GADInterstitial GADIntersticial
GADNativeExpressAdView Quitada
Anuncio de video basado en premios GADReward Quitada
Anunciodeinstream Quitada
GADInstreamAdView Quitada

Se quitaron o reemplazaron métodos

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 habían dejado de estar disponibles anteriormente.
  • Se quitaron los métodos delegados -willLeaveApplication: para todos los formatos.
  • El nombre de la clase de red de publicidad se trasladó a la propiedad GADResponseInfo.
  • El identificador de dispositivo de prueba se movió a la propiedad GADRequestConfiguration.
Clase v7.68.0 API v7.68.0 API v8.0.0 Notas
Anuncios móviles de GAD +configureWithApplicationID: -startWithCompletionHandler: El ID de la app ahora se configura en Info.plist.
+disableAutomatedInAppPurchaseReporting -disableAutomatedInAppPurchaseReporting
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest testDevices GADRequestConfiguration.testdeviceidentifiers La propiedad testDeviceIdentifiers se aplica a todas las solicitudes de anuncios, mientras que la propiedad testDevices anterior se configuraba por solicitud.
género Quitada
cumpleaños Quitada
+sdkVersion GADMobileAds.sharedInstance.sdkVersion.
-setBirthdayWithMonth:day:year: Quitada
-setLocationWithDescription: -setLocationWithLatitude:longitude:accuracy:
-tagForChildDirected externa: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedHandlingment].
GADErrorCode kGADError* Error GADError* El prefijo k se quita de todas las constantes de código de error.
GADBannerView hasAutoRefreshed autoloadEnabled
inAppPurchaseDelegate Quitada
mediatedAdView Quitada
adNetworkClassName respuestaInfo.adNetworkClassName
DFPBannerView -setValidAdSizesWithSizes: -setValidAdSizes:
DFPBannerViewOptions -adSizeDelegate Quitada
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAdWithError: -bannerView:didFailToReceiveAdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: Quitada
GADNativeCustomTemplateAd templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey:customClickHandler: -performClickOnAssetWithKey:
GADDescubrimientoImageAdLoaderOptions preferredImageOrientation GADDockerfileMediaAdOptions.mediaAspectRatio
GADInterstitial inAppPurchaseDelegate Quitada
isReady Quitada En su lugar, usa canPresentFromRootViewController:error:.
hasBeenUsed Quitada
-init -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
adNetworkClassName respuestaInfo.adNetworkClassName
-IntersticialWillLeaveApplication: Quitada
GADUnifiedContainer videoController mediaContent.videoController
adNetworkClassName respuestaInfo.adNetworkClassName