Migración del SDK

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

Migra de la versión 10 a la 11

Objetivo mínimo de implementación

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

Versión mínima de Xcode

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

Se dejarán de publicar anuncios en iOS 12

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

Se quitó la dependencia de GoogleAppMeasurement.

En la versión 11.0.0, la dependencia Se recibió GoogleAppMeasurement o quitarse. Esta dependencia que impulsó el botón de activación de las métricas del usuario en AdMob se se descontinuaron a principios de 2024. Para seguir recopilando métricas del usuario en AdMob Vincula tu app de AdMob a Firebase y integrar el SDK de Google Analytics para Firebase en tu app.

Cambios en la presentación de los anuncios de pantalla completa

Los siguientes cambios afectan los distintos formatos de anuncios:

  • Aplicación abierta
  • Intersticial
  • Recompensado
  • Intersticial recompensado

El parámetro del controlador de vista en -canPresentFromRootViewController:error: y -presentFromRootViewController: es anulable. Si se pasa "nil", 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.

Propiedades quitadas

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, pero no tiene reemplazo.

Cambios en la versión del SDK de registro

La versión 11.0.0 quita sdkVersion. Para registrar la versión del SDK de anuncios de Google para dispositivos móviles, usar 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 realiza una solicitud de anuncio si su delegate no se ajusta a los tipos de anuncios solicitados protocolo de delegado. Anteriormente, falló después de que se realizó la solicitud de anuncios.

Cambios en el comportamiento de las pruebas

Consulta la tabla en la que se muestran las condiciones actualizadas cuando ocurre lo siguiente: Las 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 Ad Manager .

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.

Requisito del ID de aplicación de Ad Manager

El ID de la app de Ad Manager ahora es obligatorio en Info.plist para todas las apps de Ad Manager y requiere el formato ca-app-pub-################~##########. Consulta Cómo actualizar el archivo Info.plist para obtener más detalles.

Requisito de GoogleAppMeasurement.xcframework

Ahora, GoogleAppMeasurement.xcframework es obligatorio para todas las apps de Ad Manager. Si instalas el SDK de anuncios de Google para dispositivos móviles mediante CocoaPods o Swift Package Manager, no se requiere ninguna acción adicional. Si instalas frameworks de forma manual, consulta Descarga manual para obtener más detalles.

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

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 Ad Manager 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.

Migrar de la versión 7 a la 8

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

Actualizaciones de la API con formato de pantalla completa

A partir de la versión 8.0.0, los anuncios intersticiales y recompensados comparten una imagen completa genérica. el estilo del anuncio de pantalla para que sea más coherente. Estas nuevas APIs de anuncios de pantalla completa tienen dos Principales diferencias 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 ligeramente. Las devoluciones de llamada de carga ya no se parte de un delegado. En su lugar, se pasan al método load como una controlador de finalización:

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

    El nuevo enfoque proporciona los siguientes beneficios:

    • Nunca tendrás una referencia a un anuncio que no se haya cargado.
    • No es necesario retener 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 GAMInterstitialAdLoadCompletionHandler o GADRewardedAdLoadCompletionHandler
    Eventos de presentación GADFullScreenContentDelegate

    Anteriormente, para escuchar cualquier evento de anuncios, registrabas una clase que implementa GADInterstitialDelegate protocolo a la propiedad delegada de un anuncio intersticial o registra una clase que implementa GADRewardedAdDelegate protocolo a la propiedad de delegado del anuncio recompensado según el formato que estás usando. Ese mismo delegado tenía métodos relacionados con la carga y el ciclo de vida de 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 único delegado antes de cargar el anuncio. Eventos de carga de anuncios, que son específicos de cada , avanza a un solo controlador de finalización de carga que se pasa en el método de carga.

Intersticial

Cargar anuncio

Los siguientes fragmentos de código muestran cómo cargar un anuncio intersticial y detectar cuando el anuncio se carga correctamente o no se carga.

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADInterstitialDelegate {

  var interstitial: DFPInterstitial!

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

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

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

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) DFPInterstitial *interstitial;

@end

@implementation ViewController

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

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

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

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  var interstitial: GAMInterstitialAd?

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

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GAMInterstitialAd *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  GAMRequest *request = [GAMRequest request];
  [GAMInterstitialAd loadWithAdUnitID:@"/21775744923/example/interstitial"
                              request:request
                    completionHandler:^(GAMInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Failed to load interstitial ad with error: %@", [error localizedDescription]);
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

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 manejar las devoluciones de llamada cuando se muestra el anuncio presenta (con o sin éxito) y cuando se descarta.

v7

Swift

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

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

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

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

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

Objective-C

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

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

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

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

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

v8

Swift

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

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

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

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

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  GAMRequest *request = [GAMRequest request];
  [GAMInterstitialAd loadWithAdUnitID:@"/21775744923/example/interstitial"
                              request:request
                    completionHandler:^(GAMInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"interstitial:didFailToReceiveAdWithError: %@", [error localizedDescription])
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

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

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

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

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(GAMRequest()) { error in
      if let error = error {
        print("Rewarded ad failed to load with error: \(error.localizedDescription)")
      } else {
        print("Rewarded ad loaded.")
      }
    }
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

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

v8

Swift

import GoogleMobileAds
import UIKit

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

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

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  GAMRequest *request = [GAMRequest request];
  [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                          request:request
                completionHandler:^(GADRewardedAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
      return;
    }
    self.rewardedAd = ad;
    NSLog(@"Rewarded ad loaded.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

Anuncio gráfico y recompensa

Los anuncios recompensados requieren que controles el evento cuando un usuario obtiene una recompensa. Con versión 7 de la API de GADRewardedAd, implementarás rewardedAd:userDidEarnReward: como parte del protocolo GADRewardedAdDelegate En la versión 8, implementarás GADUserDidEarnRewardHandler para hacer lo siguiente: 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 una GADFullscreenContentDelegate como una propiedad en el anuncio antes de presentar la 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 rewarded ad was presented.
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

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

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

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

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

v8

Swift

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

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

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  GAMRequest *request = [GAMRequest request];
  [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                          request:request
                completionHandler:^(GADRewardedAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
      return;
    }
    self.rewardedAd = ad;
    NSLog(@"Rewarded ad loaded.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

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

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

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

Eliminación de la API de GADRecompensaBasedVideoAd heredada

El nuevo GADRewardedAd La API se introdujo por primera vez en marzo de 2019 y ha sido la API preferida API desde hace más de 18 meses. Tiene más mejoras que la versión heredada API de GADRewardedBasedVideoAd, incluida la capacidad de cargar más de una anuncio recompensado a la vez.

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

Baja del banner inteligente y se reemplazó por los banners adaptables

Los anuncios de banners inteligentes dejaron de estar disponibles para priorizar el uso de banners adaptables anuncios. Los banners adaptables brindan un rendimiento superior y más flexibilidad en la configuración del ancho del anuncio. Si prefieres seguir usando banners de ancho completo, puedes aún se puede realizar con el 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

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

Se aplicó la devolución de llamada willLeaveApplication para todos los formatos de anuncios. quitada para dar lugar a la applicationDidEnterBackground: y sceneDidEnterBackground: . El uso de APIs a nivel del SO te notifican cada vez que los usuarios abandonan 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 tuvo como objetivo ser un controlador de clics de anuncios, y depender de esta devolución de llamada para informar los clics no para generar una métrica precisa. Por ejemplo, un clic en AdChoices que iniciaba un navegador externo invocaba la devolución de llamada, pero no contaba o hacer clic.

Cambio de nombre de la clase

En la siguiente tabla, se indican nombres de clases específicas que se modificaron o se quitaron en versión 8. Resumen:

  • Se cambió el nombre de todas las clases relacionadas con GADUnifiedNativeAd a GADNativeAd
  • GADRewardBasedVideoAd, GADNativeExpressAdView y GADInstreamAd tienen se ha eliminado.
  • Todas las clases con el prefijo DFP se reemplazaron por el prefijo GAM.
Clase v7.68.0 Clase v8.0.0
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial GAMInterstitialAd
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedPad GADNativeAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNativeAd
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase Quitada
GADInterstitial GADInterstitialAd
GADNativeExpressAdView Quitada
GADRewardBasedVideoAd Quitada
GADInstreamAd Quitada
GADInstreamAdView Quitada

Se quitaron o reemplazaron métodos

En la siguiente tabla, se indican los cambios específicos implementados en la versión 8. Resumen:

  • Se quitaron los métodos y las propiedades que dejaron de estar disponibles anteriormente.
  • Se quitaron -willLeaveApplication: métodos delegados para todos los formatos.
  • El nombre de clase de la red de publicidad se movió a la propiedad GADResponseInfo.
  • El identificador del dispositivo de prueba se movió a GADRequestConfiguration propiedad.
Clase v7.68.0 API v7.68.0 API v8.0.0 Notas
GADMobileAds +configureWithApplicationID: -startWithCompletionHandler: El ID de la app ahora está configurado 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 La propiedad testDevices anterior se configuró por solicitud.
género Quitada
cumpleaños Quitada
+sdkVersion GADMobileAds.sharedInstance.sdkVersion
-setBirthdayWithMonth:day:year: Quitada
-setLocationWithDescription: -setLocationWithLatitude:longitude:accuracy:
-tagForChildDirectedTreatment. [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment].
GADErrorCode kGADError* GADError* El prefijo k se descarta de todas las constantes de código de error.
GADBannerView hasAutoRefreshed autoloadEnabled
inAppPurchaseDelegate Quitada
mediatedAdView Quitada
adNetworkClassName responseInfo.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:
GADNativeAdImageAdLoaderOptions preferredImageOrientation GADNativeAdMediaAdOptions.mediaAspectRatio
GADInterstitial inAppPurchaseDelegate Quitada
isReady Quitada En su lugar, usa canPresentFromRootViewController:error:.
hasBeenUsed Quitada
-init -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
adNetworkClassName responseInfo.adNetworkClassName
-interstitialWillLeaveApplication: Quitada
GADUnifiedPad videoController mediaContent.videoController
adNetworkClassName responseInfo.adNetworkClassName