Migração do SDK

Esta página aborda as migrações das versões atual e anterior do SDK dos anúncios para dispositivos móveis do Google para iOS. A versão 11.0.0 deve ser lançada em janeiro de 2024.

Migrar da versão v10 do SDK para a v11

Destino mínimo de implantação

O destino mínimo de implantação foi aumentado para o iOS 12.

Versão mínima do Xcode

A versão mínima do Xcode compatível foi aumentada para 15.1.

A veiculação de anúncios será interrompida no iOS 12

A versão 11.0.0 do SDK dos anúncios para dispositivos móveis do Google veicula anúncios somente em dispositivos com o iOS 13 e versões mais recentes.

Remoção da dependência GoogleAppMeasurement

Na versão 11.0.0, a dependência de GoogleAppMeasurement foi removida. Essa dependência que ativou a alternância de métricas do usuário na AdMob vai ser descontinuada no início de 2024. Para continuar coletando métricas do usuário na AdMob, vincule seu app da AdMob ao Firebase e integre o SDK do Google Analytics para Firebase ao seu aplicativo.

Mudanças na apresentação de anúncios em tela cheia

As seguintes mudanças afetam os diversos formatos de anúncio:

  • Abertura do app
  • Intersticial
  • Premiado
  • Intersticial premiado

O parâmetro do controlador de visualização em -canPresentFromRootViewController:error: e -presentFromRootViewController: é anulável. Se nulo for transmitido, o anúncio será apresentado do controlador de visualização de nível mais alto na hierarquia dele.

Métodos removidos

Os métodos a seguir foram removidos.

Tipo v11.0.0 Método Observações
GADAppOpenAd load(withAdUnitID adUnitID: String, request: GADRequest?, orientation: UIInterfaceOrientation) Use load(withAdUnitID adUnitID: String, request: GADRequest?).
GADMediationBannerAdEventDelegate willBackgroundApplication() Sem substituição.
GADMediationInterstitialAdEventDelegate willBackgroundApplication() Sem substituição.
GADMediationNativeAdEventDelegate willBackgroundApplication() Sem substituição.
GADMediationRewardedAdEventDelegate didRewardUser(with reward: GADAdReward) Use didRewardUser().
GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdWillLeaveApplication(_ mediatedNativeAd: GADMediatedUnifiedNativeAd) Sem substituição.
GADRequestConfiguration setSameAppKeyEnabled(_ enabled: Bool) Use setPublisherFirstPartyIDEnabled(_ enabled: Bool)
tagForUnderAge(ofConsent underAgeOfConsent: Bool) Use a propriedade tagForUnderAgeOfConsent.
tag(forChildDirectedTreatment childDirectedTreatment: Bool) Use a propriedade tagForChildDirectedTreatment.

Propriedades removidas

As propriedades a seguir foram removidas.

Classe v11.0.0 Propriedade Observações
GADMediationAdConfiguration hasUserLocation Sem substituição.
userLatitude
userLongitude
userLocationAccuracyInMeters
childDirectedTreatment Use GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment.
GADResponseInfo adNetworkClassName Use adNetworkClassName de loadedAdNetworkResponseInfo.

GADAdFormatUnknown removido

GADAdFormatUnknown foi removido sem substituição.

Mudanças na versão do SDK do Logging

A versão 11.0.0 remove sdkVersion. Para registrar a versão do SDK dos anúncios para dispositivos móveis do Google, use versionNumber.

Versão 10.0.0

GADMobileAds.sharedInstance().sdkVersion

Versão 11.0.0

GADGetStringFromVersionNumber(GADMobileAds.sharedInstance().versionNumber)

Alterações no tratamento de erros do GADAdLoader

A partir da versão 11.0.0, GADAdLoader não faz uma solicitação de anúncio se o delegate não estiver em conformidade com o protocolo de delegação dos tipos de anúncios solicitados. Anteriormente, isso falhava após a solicitação de anúncio ser feita.

Mudanças no comportamento de testes

Consulte a tabela que mostra as condições atualizadas para quando as propriedades a seguir retornarem true.

Turma Propriedade
GADMediationAdConfiguration isTestRequest
GADCustomEventRequest isTesting
v10.0.0 v11.0.0
  • O dispositivo é declarado explicitamente como um dispositivo de teste em testDeviceIdentifiers.
  • O dispositivo é declarado explicitamente como um dispositivo de teste em testDeviceIdentifiers.
  • O dispositivo é um simulador.
  • O dispositivo é declarado explicitamente como um dispositivo de teste na interface AdMob .

Migrar da v9 para a v10

A veiculação de anúncios é interrompida no iOS 11

A versão 10.0.0 do SDK dos anúncios para dispositivos móveis do Google veicula anúncios somente em dispositivos com o iOS 12 e versões mais recentes.

O upgrade para a versão 10.0.0 do SDK dos anúncios para dispositivos móveis do Google não vai corromper seu app nos dispositivos iOS 11 e iOS 10. No entanto, nenhum anúncio será veiculado nesses dispositivos.

Não há mais suporte para criação com bitcode

Agora é preciso desativar o bitcode nos seus apps para dispositivos móveis para integrar o SDK dos anúncios para dispositivos móveis do Google.

Tipos removidos

Tipo Observações
GADGender Sem substituição.
GADMRewardBasedVideoAdNetworkAdapterProtocol Todos os adaptadores de mediação premiada listados em Escolher redes pararam de usar esses protocolos há mais de um ano. Use o GADMediationAdapter para mediação e eventos personalizados.
GADMRewardBasedVideoAdNetworkConnectorProtocol

Propriedades removidas

As propriedades a seguir são removidas sem substituição.

Classe v10.0.0 Propriedade
GADMediationAdRequest userBirthday
userGender
userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription
GADCustomEventRequest userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription

Migrar da v8 para a v9

A veiculação de anúncios é interrompida no iOS 10

A versão 9.0.0 mínima compatível com o SDK dos anúncios para dispositivos móveis do Google é o iOS 11.

O upgrade para a versão 9.0.0 do SDK dos anúncios para dispositivos móveis do Google não vai causar falhas no seu app em dispositivos iOS 10. No entanto, nenhum anúncio será veiculado nesses dispositivos.

Aplicação mais rigorosa dos controles da barra de status

A partir da versão 9.0.0, quando você apresenta anúncios em formato de tela cheia, seu app precisa garantir que os anúncios possam controlar a apresentação da barra de status. Se você não fizer isso, uma mensagem de erro vai aparecer nos registros.

Dependendo do layout específico dos controladores de visualização no app, talvez não seja necessário fazer mudanças para garantir isso. Considere se você precisa definir a propriedade childViewControllerForStatusBarHidden no rootViewController do anúncio.

Renomeação de adDidPresentFullScreenContent: para adWillPresentFullScreenContent:

Não há mudança de comportamento. O método delegado é invocado antes do anúncio estar prestes a ser apresentado. Portanto, o novo nome do método reflete melhor a funcionalidade dele.

Remover a API de configuração de localização em GADRequest

O - (void)setLocationWithLatitude:longitude:accuracy: foi excluído de GADRequest porque os dados de local não são usados pelo Google para segmentar anúncios. Se necessário, use APIs de terceiros para fornecer informações a redes de publicidade terceirizadas.

Descontinuação das interfaces de eventos personalizados

Os eventos personalizados permitem que os editores que usam a mediação AdMob adicionem a mediação em hierarquia para uma rede de publicidade que não é uma das redes de publicidade compatíveis.

Todos os protocolos de eventos personalizados foram descontinuados. Em vez disso, use os protocolos GADMediationAdapter e GADMediationAdEventDelegate para ter as mesmas funcionalidades. Essa mudança melhora a clareza e permite criar eventos personalizados para anúncios premiados e anúncios interscroller que não estavam disponíveis anteriormente.

APIs

A tabela abaixo lista as APIs de adaptador de mediação correspondentes às APIs de eventos personalizados que precisam ser usadas a partir da versão 9.0.0.

v8 v9
GADCustomEventBanner
GADCustomEventIntersticial
GADCustomEventNativeAd
GADMediationAdapter GADMediationBannerAd
GADMediationIntersticialAd
GADMediationInterscrollerAd
GADMediationRewardedAd
GADMediationNativeAd
delegate O delegado é retornado pelo gerenciador de conclusão do carregamento de cada função de carregamento da classe GADMediationAdapter.
-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

Delegar métodos

A tabela abaixo lista os métodos correspondentes de delegação de evento de anúncio de mediação para métodos personalizados de delegação de eventos que devem ser usados a partir da versão 9.0.0.

v8 v9
GADCustomEventBannerDelegate
GADCustomEventIntersticialDelegate
GADCustomEventNativeAdDelegate
GADMediationAdEventDelegate GADMediationAd
-customEventBanner:didReceiveAd:
-customEventInterstitialDidReceiveAd:
O status de carregamento do anúncio é incluído no gerenciador de conclusão de carregamento de cada função de carregamento na classe GADMediationAdapter.
-customEventBanner:didFailAd:
-customEventInterstitial:didFailAd:
-customEventBannerWasClicked:
-customEventInterstitialWasClicked:
-reportClick
-customEventBannerWillPresentModal:
-customEventInterstitialWillPresentModal:
-willPresentFullScreenView
-customEventBannerWillDismissModal:
-customEventInterstitialWillDismissModal:
-willDismissFullScreenView
-customEventBannerDidDismissModal:
-customEventInterstitialDidDismissModal:
-didDismissFullScreenView
-customEventBannerWillLeaveApplication:
-customEventInterstitialWillLeaveApplication:
-willBackgroundApplication
viewControllerForPresentingModalView -[GADMediationBannerAd view]

Outros métodos e constantes removidos/substituídos

Mudanças no método, constante ou propriedade
Constantes com prefixo kGAD- Removido. Use constantes com prefixo GAD-.
GADAdNetworkResponseInfo credentials foram removidos. Use adUnitMapping.
GAMRequest O uso de kGAMSimulatorID em GAMRequest foi descontinuado. Em vez disso, use GADSimulatorID em GADRequestConfiguration.
GADCustomNativeAd O uso de mediaView em GADCustomNativeAd foi descontinuado. Em vez disso, use mediaContent.
APIs In-App Purchase em GoogleMobileAds As APIs inAppPurchase em GoogleMobileAds foram removidas

Migrar da v7 para a v8

A versão 8.0.0 do SDK dos anúncios para dispositivos móveis do Google apresenta algumas mudanças importantes, além de algumas renomeações e remoções de APIs.

Atualizações da API em formato de tela cheia

A partir da versão 8.0.0, os anúncios intersticiais e premiados compartilham um estilo de anúncio genérico de tela cheia para maior consistência. Essas novas APIs de anúncios em tela cheia têm duas principais distinções das APIs de anúncios em tela cheia da versão 7:

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

    A abordagem anterior para carregar/exibir um anúncio de tela cheia é a seguinte:

    1. Crie uma instância de objeto de anúncio e mantenha uma referência a ela.
    2. Atribua um delegado que processe o carregamento e mostre callbacks.
    3. Carregar um anúncio.
    4. Verifique se o anúncio está carregado usando isReady.
    5. Veicular o anúncio.

    Na versão 8, a abordagem muda um pouco. Callbacks de carregamento não fazem mais parte de um delegado. Em vez disso, elas são transmitidas para o método load como um gerenciador de conclusão:

    1. Chame um método de carregamento estático na classe de anúncio e forneça um gerenciador de conclusão de carregamento.
    2. No retorno de chamada de conclusão do carregamento, mantenha uma referência ao anúncio carregado que foi retornado.
    3. Atribua um delegado que processe callbacks de shows.
    4. Veicular o anúncio.

    A nova abordagem oferece os seguintes benefícios:

    • Nunca haverá uma referência a um anúncio que não foi carregado.
    • Não é necessário segurar um objeto de anúncio enquanto ele está carregando.
  2. Eventos de anúncios consistentes.

    Tipo de evento API atual API v8
    Eventos de carregamento GADInterstitialDelegate ou GADRewardedAdDelegate GADInterstitialAdLoadCompletionHandler ou GADRewardedAdLoadCompletionHandler
    Eventos de apresentação GADFullScreenContentDelegate

    Antes, para detectar eventos de anúncios, era necessário registrar uma classe que implementa o protocolo GADInterstitialDelegate na propriedade delegada de um intersticial ou uma classe que implementa o protocolo GADRewardedAdDelegate na propriedade de delegação de um anúncio premiado, dependendo do formato que você estiver usando. Esse mesmo delegado tinha métodos relacionados ao ciclo de vida de carregamento e da apresentação de um anúncio.

    Na versão 8, os eventos de carregamento e de apresentação são separados. Agora você pode registrar um GADFullScreenContentDelegate a qualquer momento antes de mostrar um anúncio, em vez de definir um único delegado antes de carregar o anúncio. Eventos de carregamento de anúncios, que são específicos para cada formato, passam para um único gerenciador de conclusão de carregamento transmitido no método de carregamento.

Intersticial

Carregar anúncio

Os snippets de código abaixo mostram como carregar um anúncio intersticial e detectar eventos de sucesso ou falha no carregamento.

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

Anúncio de display

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 anúncio de apresentação

Os snippets de código abaixo mostram como processar callbacks para quando o anúncio é exibido (com ou sem sucesso) e quando ele é dispensado.

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

Premiado

Carregar anúncio

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

Anúncio de display e gerenciamento do prêmio

Nos anúncios premiados, é necessário lidar com o evento quando um usuário ganha um prêmio. Com a versão 7 da API GADRewardedAd, você implementa rewardedAd:userDidEarnReward: como parte do protocolo GADRewardedAdDelegate. Na versão 8, implemente GADUserDidEarnRewardHandler para apresentar o anúncio.

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 anúncio de apresentação

Com a API GADRewardedAd, você transmite um GADRewardedAdDelegate para o método que apresenta o anúncio. Com a API GADRewardedAd, você define uma GADFullscreenContentDelegate como uma propriedade no anúncio antes de apresentá-lo.

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

Remoção da API GADRewardedBasedVideoAd legada

A API GADRewardedAd mais recente foi lançada em março de 2019 e tem sido a API premiada preferencial por mais de 18 meses. Ela teve mais melhorias em comparação com a API GADRewardedBasedVideoAd legada, incluindo a capacidade de carregar mais de um anúncio premiado por vez.

A API GADRewardedBasedVideoAd legada foi removida na versão 8.0.0 do SDK.

Descontinuação do banner inteligente para uso do banner adaptativo

Os anúncios de banner inteligente foram descontinuados e substituídos por anúncios de banner adaptativo. Os banners adaptativos oferecem desempenho superior e mais flexibilidade na configuração da largura do anúncio. Se você preferir continuar usando banners de largura total, isso ainda poderá ser feito usando o banner adaptativo, conforme mostrado no snippet de código a seguir:

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

Sair da remoção do callback do app

O callback willLeaveApplication para todos os formatos de anúncio foi removido e substituído pelos métodos applicationDidEnterBackground: e sceneDidEnterBackground:. O uso de APIs no nível do SO notifica você sempre que os usuários saem do seu app, independentemente de uma interação com o anúncio ou não.

O callback willLeaveApplication não foi criado para ser um gerenciador de cliques no anúncio, e usar esse callback para informar os cliques não gerou uma métrica precisa. Por exemplo, um clique no ícone "Opções de anúncios" que iniciou um navegador externo invocou o retorno de chamada, mas não contou um clique.

Renomeação de turmas

A tabela abaixo lista nomes de classes específicos que foram alterados ou removidos na versão 8. Resumindo:

  • Todas as classes relacionadas a GADUnifiedNativeAd foram renomeadas como GADNativeAd
  • GADRewardBasedVideoAd, GADNativeExpressAdView e GADInstreamAd foram removidos.
  • Todas as classes com o prefixo DFP foram substituídas por um prefixo GAM.
Classe v7.68.0 Classe v8.0.0
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial AnúncioIntersticial GAM
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedNativeAd GADNativeAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNativeAd
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase Removida
GADInterstitial GADIntersticial
GADNativeExpressAdView Removida
GAD RewardsBasedVideoAd Removida
Anúncio In-stream Removida
GADInstreamAdView Removida

Métodos removidos/substituídos

A tabela abaixo lista as mudanças específicas da versão 8. Resumindo:

  • Métodos e propriedades descontinuados foram removidos.
  • Os métodos delegados -willLeaveApplication: foram removidos de todos os formatos.
  • O nome da classe da rede de publicidade foi movido para a propriedade GADResponseInfo.
  • O identificador de dispositivo de teste foi movido para a propriedade GADRequestConfiguration.
Classe v7.68.0 API v7.68.0 API v8.0.0 Observações
Anúncios para dispositivos móveis +configureWithApplicationID: -startWithConclusãoHandler: O ID do app está definido em Info.plist.
+disableAutomatedInAppRelatórios de compras -Relatórios de comprasdisableAutomatedInApp
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest testDevices GADRequestConfiguration.testdeviceidentifiers A propriedade testDeviceIdentifiers se aplica a todas as solicitações de anúncios, enquanto a antiga propriedade testDevices era definida por solicitação.
gênero Removida
aniversário Removida
+sdkVersion GADMobileAds.sharedInstance.sdkVersion
-setBirthdayWithMonth:day:year: Removida
-setLocationWithDescription: -setLocationWithLatitude:longitude:accuracy:
-tagForChildDirectedTreatment: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment]
GADErrorCode kGADError* GADError* O prefixo k é removido de todas as constantes de código de erro.
GADBannerView hasAutoRefreshed autoloadEnabled
inAppPurchaseDelegate Removida
mediatedAdView Removida
adNetworkClassName responseInfo.adNetworkClassName
DFPBannerView -setValidAdSizesWithSizes: -setValidAdSizes:
DFPBannerViewOptions –adSizeDelegate Removida
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAdWithError: -bannerView:didFailToReceiveAdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeadApplication: Removida
GADNativeCustomTemplateAd templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey:customClickHandler: -performClickOnAssetWithKey:
GADNativeAdImageAdLoaderOptions preferredImageOrientation GADNativeAdMediaAdOptions.mediaAspectRatio
GADInterstitial inAppPurchaseDelegate Removida
isReady Removida Use canPresentFromRootViewController:error:.
hasBeenUsed Removida
-init -initWithAdIDID:
-setgclidID: -initWithAdIDID:
adNetworkClassName responseInfo.adNetworkClassName
-IntersticialWillExitApplication: Removida
GADUnifiedNativeAd videoController mediaContent.videoController
adNetworkClassName responseInfo.adNetworkClassName