Pré-carregamento de anúncios (Alfa)

Selecione a plataforma: Android (Beta) Novo Android iOS Unity

O pré-carregamento de anúncios é um recurso de carregamento de anúncios gerenciado pelo Google no Google Mobile Ads SDK que gerencia o carregamento e o armazenamento em cache de anúncios em seu nome. O pré-carregamento de anúncios exige uma mudança na forma de gerenciar o carregamento. Para otimizar a performance usando o pré-carregamento de anúncios, desative o armazenamento em cache personalizado e delegue essa responsabilidade ao Google Mobile Ads SDK.

O pré-carregamento de anúncios oferece os seguintes benefícios em relação ao carregamento manual:

  • Gerenciamento de referências:mantém os anúncios carregados para que você não precise manter referências até que esteja tudo pronto para mostrá-los.
  • Recarga automática:carrega automaticamente um novo anúncio quando você retira um do cache.
  • Repetições gerenciadas:repete automaticamente solicitações com falha usando espera exponencial.
  • Processamento de expiração:atualiza automaticamente os anúncios antes que eles expirem (normalmente após uma hora).
  • Otimização de cache:se você usar um tamanho de cache maior que um, o Google Mobile Ads SDK otimizará a ordem do cache para veicular o melhor anúncio.

Este guia explica como configurar anúncios de pré-carregamento, verificar a disponibilidade deles e mostrar o anúncio pré-carregado.

Pré-requisitos

Antes de continuar com o tutorial, conclua os seguintes itens:

  • Instale a versão 12.6.0 ou mais recente do Google Mobile Ads SDK. Os recursos para desenvolvedores de versões anteriores estão disponíveis em 11.12.0 - 12.2.0, mas recomendamos usar a versão 12.6.0 ou mais recente e seguir este guia daqui para frente.
  • Configure o Google Mobile Ads SDK.

Começar a pré-carregar anúncios

Para começar a pré-carregar anúncios, chame preload(). Chame esse método apenas uma vez no início do app. Depois de chamar preload(), o Google Mobile Ads SDK faz o pré-carregamento automático de anúncios e tenta novamente as solicitações com falha para configurações pré-carregadas.

O exemplo a seguir começa a pré-carregar anúncios:

Swift

// Start the preloading initialization process.
let request = Request()
let interstitialConfig = PreloadConfigurationV2(
  adUnitID: Constants.interstitialAdUnitID, request: request)
InterstitialAdPreloader.shared.preload(
  for: Constants.interstitialAdUnitID, configuration: interstitialConfig, delegate: self)

Objective-C

// Start the preloading initialization process.
GADRequest *request = [GADRequest request];
GADPreloadConfigurationV2 *interstitialConfig = [[GADPreloadConfigurationV2 alloc] initWithAdUnitID:interstitialAdUnitID request:request];

[GADInterstitialAdPreloader.sharedInstance preloadForPreloadID:interstitialAdUnitID
                                                     configuration:interstitialConfig
                                                          delegate:self];

Receber e mostrar o anúncio pré-carregado

Ao usar o pré-carregamento de anúncios, Google Mobile Ads SDK armazena anúncios em cache. Quando quiser mostrar um anúncio, chame adWithPreloadID(). Google Mobile Ads SDK recupera o anúncio disponível e pré-carrega automaticamente o próximo anúncio em segundo plano.

Evite chamar esse método até que esteja tudo pronto para mostrar um anúncio. Manter os anúncios no cache permite que o Google Mobile Ads SDK atualize automaticamente os anúncios expirados e faça a otimização do cache.

O exemplo a seguir recupera e mostra um anúncio pré-carregado:

Swift

private func showInterstitialAd() {
  // Verify that the preloaded ad is available before polling.
  guard isInterstitialAvailable() else {
    printAndShowAlert("Preload interstitial ad is exhausted.")
    return
  }

  // Polling returns the next available ad and load another ad in the background.
  let ad = InterstitialAdPreloader.shared.ad(with: Constants.interstitialAdUnitID)

  // Interact with the ad object as needed.
  print("Interstitial ad response info: \(String(describing: ad?.responseInfo))")
  ad?.paidEventHandler = { (value: AdValue) in
    print("Interstitial ad paid event: \(value.value), \(value.currencyCode)")
  }

  ad?.fullScreenContentDelegate = self
  ad?.present(from: self)
}

Objective-C

- (void)showInterstitialAd {
  // Verify that the preloaded ad is available before polling.
  if (![self isInterstitialAvailable]) {
    [self logAndShowAlert:@"Preloaded interstitial ad is not available."];
    return;
  }

  // Getting the preloaded ad loads another ad in the background.
  GADInterstitialAd *ad = [GADInterstitialAdPreloader.sharedInstance adWithPreloadID:interstitialAdUnitID];

  // Interact with the ad object as needed.
  NSLog(@"Interstitial ad response info: %@", ad.responseInfo);
  ad.paidEventHandler = ^(GADAdValue *_Nonnull value) {
    NSLog(@"Interstitial ad paid event: %@ %@ ", value.value, value.currencyCode);
  };
  ad.fullScreenContentDelegate = self;
  [ad presentFromRootViewController:self];
}

Verificar a disponibilidade de anúncios de pré-carregamento

Para verificar a disponibilidade de anúncios, escolha uma das seguintes opções:

Receber a disponibilidade de anúncios pré-carregados

O exemplo a seguir verifica a disponibilidade de anúncios:

Swift

private func isInterstitialAvailable() -> Bool {
  // Verify that an ad is available before polling.
  return InterstitialAdPreloader.shared.isAdAvailable(with: Constants.interstitialAdUnitID)
}

Objective-C

- (BOOL)isInterstitialAvailable {
  // Verify that an ad is available before polling.
  return [GADInterstitialAdPreloader.sharedInstance isAdAvailableWithPreloadID:(interstitialAdUnitID)];
}

Detectar a disponibilidade de anúncios pré-carregados

Registre-se para receber notificações quando os anúncios forem pré-carregados, não forem pré-carregados ou o cache de anúncios estiver esgotado.

Os eventos de pré-carregamento são destinados a fins de análise. Dentro dos callbacks de eventos de pré-carregamento:

  • Não chame o preload().
  • Evite chamar adWithPreloadID(), a menos que o anúncio seja mostrado imediatamente.

O exemplo a seguir registra eventos de anúncio:

Swift

func adAvailable(forPreloadID preloadID: String, responseInfo: ResponseInfo) {
  // This callback indicates that an ad is available for the specified configuration.
  // No action is required here, but updating the UI can be useful in some cases.
  print("Ad preloaded successfully for ad preload ID: \(preloadID)")
  // ...
}

func adsExhausted(forPreloadID preloadID: String) {
  // This callback indicates that all the ads for the specified configuration have been
  // consumed and no ads are available to show. No action is required here, but updating
  // the UI can be useful in some cases.
  // [Important] Don't call AdPreloader.shared.preload or AdPreloader.shared.ad
  // from adsExhausted.
  print("Ad exhausted for ad preload ID: \(preloadID)")
  // ...
}

func adFailedToPreload(forPreloadID preloadID: String, error: Error) {
  print(
    "Ad failed to load with ad preload ID: \(preloadID), Error: \(error.localizedDescription)"
  )
}

Objective-C

- (void)adAvailableForPreloadID:(nonnull NSString *)preloadID responseInfo:(nonnull GADResponseInfo *)responseInfo {
  // This callback indicates that an ad is available for the specified configuration.
  // No action is required here, but updating the UI can be useful in some cases.
  NSLog(@"Ad preloaded successfully for ad unit ID: %@", preloadID);
  // ...
}

- (void)adsExhaustedForPreloadID:(nonnull NSString  *)preloadID {
  // This callback indicates that all the ads for the specified configuration have been
  // consumed and no ads are available to show. No action is required here, but updating
  // the UI can be useful in some cases.
  // [Important] Don't call [GAD<Format>AdPreloader preloadForPreloadID:] or
  // [GAD<Format>AdPreloader adWithPreloadID:] from adsExhaustedForPreloadID.
  NSLog(@"Ad exhausted for ad preload ID: %@", preloadID);
  // ...
}

- (void)adFailedToPreloadForPreloadID:(nonnull NSString  *)preloadID error:(nonnull NSError *)error {
  NSLog(@"Ad failed to load with ad preload ID: %@, Error: %@", preloadID, error.localizedDescription);
}

Interromper a pré-carga de anúncios

Se você não precisar mostrar anúncios para um ID de pré-carga novamente na sessão, pare de pré-carregar anúncios. Para interromper o pré-carregamento de anúncios para um ID de pré-carregamento específico, chame stopPreloadingAndRemoveAdsForPreloadID() com um ID de pré-carregamento.

Definir o tamanho do buffer

O tamanho do buffer controla o número de anúncios pré-carregados mantidos na memória. Por padrão, o Google otimiza o tamanho do buffer para equilibrar o consumo de memória e a latência da veiculação de anúncios. Se o app mostrar anúncios antes do carregamento do próximo, defina um tamanho de buffer personalizado para aumentar o número de anúncios mantidos na memória. Recomendamos um tamanho de buffer de no máximo quatro.

Swift

let preloadConfig = PreloadConfigurationV2(adUnitID: "/21775744923/example/rewarded")
preloadConfig.bufferSize = 3

Objective-C

GADPreloadConfigurationV2 *preloadConfig =
    [[GADPreloadConfigurationV2 alloc] initWithAdUnitID:@"/21775744923/example/rewarded"];
preloadConfig.bufferSize = 3;