Eventos personalizados de anúncios intersticiais

Pré-requisitos

Conclua a configuração de eventos personalizados.

Solicitar um anúncio intersticial

Quando o item de linha do evento personalizado é alcançado na cadeia de mediação em hierarquia, the loadInterstitial:adConfiguration:completionHandler: method é chamado no nome da classe fornecido ao criar um evento personalizado. Nesse caso, esse método está em SampleCustomEvent, que chama the loadInterstitial:adConfiguration:completionHandler: method em SampleCustomEventInterstitial.

Para solicitar um anúncio intersticial, crie ou modifique uma classe que implemente GADMediationAdapter e loadInterstitial:adConfiguration:completionHandler:. Se uma classe que estende GADMediationAdapter já existir, implemente loadInterstitial:adConfiguration:completionHandler: nela. Além disso, crie uma nova classe para implementar GADMediationInterstitialAd.

Em nosso exemplo de evento personalizado, SampleCustomEvent implementa the GADMediationAdapter interface e, em seguida, delega para SampleCustomEventInterstitial.

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, GADMediationAdapter {

  fileprivate var interstitialAd: SampleCustomEventInterstitial?
  ...

  func loadInterstitial(
    for adConfiguration: GADMediationInterstitialAdConfiguration,
    completionHandler: @escaping GADMediationInterstitialLoadCompletionHandler
  ) {
    self.interstitialAd = SampleCustomEventInterstitial()
    self.interstitialAd?.loadInterstitial(
      for: adConfiguration, completionHandler: completionHandler)
  }
}

Objective-C

#import "SampleCustomEvent.h"

@implementation SampleCustomEvent

SampleCustomEventInterstitial *sampleInterstitial;

- (void)loadInterstitialForAdConfiguration:
            (GADMediationInterstitialAdConfiguration *)adConfiguration
                         completionHandler:
                             (GADMediationInterstitialLoadCompletionHandler)
                                 completionHandler {
  sampleInterstitial = [[SampleCustomEventInterstitial alloc] init];
  [sampleInterstitial loadInterstitialForAdConfiguration:adConfiguration
                                       completionHandler:completionHandler];
}

OSampleCustomEventInterstitial é responsável pelas seguintes tarefas:

  • Carregar o anúncio intersticial e invocarGADMediationInterstitialAdLoadCompletionHandler method após a conclusão do carregamento

  • Implementar o GADMediationInterstitialAd protocol

  • Receber e relatar callbacks de eventos de anúncios para o SDK dos anúncios para dispositivos móveis do Google.

O parâmetro opcional definido na interface AdMob é incluído na configuração do anúncio. O parâmetro pode ser acessado usando adConfiguration.credentials.settings[@"parameter"]. Esse parâmetro normalmente é um identificador de bloco de anúncios exigido por um SDK de rede de publicidade ao instanciar um objeto de anúncio.

Swift

import GoogleMobileAds

class SampleCustomEventInterstitial: NSObject, GADMediationInterstitialAd {
  /// The Sample Ad Network interstitial ad.
  var interstitial: SampleInterstitial?

  /// The ad event delegate to forward ad rendering events to the Google Mobile Ads SDK.
  var delegate: GADMediationInterstitialAdEventDelegate?

  var completionHandler: GADMediationInterstitialLoadCompletionHandler?

  func loadInterstitial(
    for adConfiguration: GADMediationInterstitialAdConfiguration,
    completionHandler: @escaping GADMediationInterstitialLoadCompletionHandler
  ) {
    interstitial = SampleInterstitial.init(
      adUnitID: adConfiguration.credentials.settings["parameter"] as? String)
    interstitial?.delegate = self
    let adRequest = SampleAdRequest()
    adRequest.testMode = adConfiguration.isTestRequest
    self.completionHandler = completionHandler
    interstitial?.fetchAd(adRequest)
  }

  func present(from viewController: UIViewController) {
    if let interstitial = interstitial, interstitial.isInterstitialLoaded {
      interstitial.show()
    }
  }
}

Objective-C

#import "SampleCustomEventInterstitial.h"

@interface SampleCustomEventInterstitial () <SampleInterstitialAdDelegate,
                                             GADMediationInterstitialAd> {
  /// The sample interstitial ad.
  SampleInterstitial *_interstitialAd;

  /// The completion handler to call when the ad loading succeeds or fails.
  GADMediationInterstitialLoadCompletionHandler _loadCompletionHandler;

  /// The ad event delegate to forward ad rendering events to the Google Mobile
  /// Ads SDK.
  id <GADMediationInterstitialAdEventDelegate> _adEventDelegate;
}
@end

- (void)loadInterstitialForAdConfiguration:
            (GADMediationInterstitialAdConfiguration *)adConfiguration
                         completionHandler:
                             (GADMediationInterstitialLoadCompletionHandler)
                                 completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationInterstitialLoadCompletionHandler
      originalCompletionHandler = [completionHandler copy];

  _loadCompletionHandler = ^id<GADMediationInterstitialAdEventDelegate>(
      _Nullable id<GADMediationInterstitialAd> ad, NSError *_Nullable error) {
    // Only allow completion handler to be called once.
    if (atomic_flag_test_and_set(&completionHandlerCalled)) {
      return nil;
    }

    id<GADMediationInterstitialAdEventDelegate> delegate = nil;
    if (originalCompletionHandler) {
      // Call original handler and hold on to its return value.
      delegate = originalCompletionHandler(ad, error);
    }

    // Release reference to handler. Objects retained by the handler will also
    // be released.
    originalCompletionHandler = nil;

    return delegate;
  };

  NSString *adUnit = adConfiguration.credentials.settings[@"parameter"];
  _interstitialAd = [[SampleInterstitial alloc] initWithAdUnitID:adUnit];
  _interstitialAd.delegate = self;
  SampleAdRequest *adRequest = [[SampleAdRequest alloc] init];
  adRequest.testMode = adConfiguration.isTestRequest;
  [_interstitialAd fetchAd:adRequest];
}

Independentemente de o anúncio ser buscado ou encontrar um erro, você chama GADMediationInterstitialLoadCompletionHandler. Em caso de sucesso, transmita a classe que implementa GADMediationInterstitialAd com um valor nil para o parâmetro de erro. Em caso de falha, transmita o erro encontrado.

Normalmente, esses métodos são implementados dentro de callbacks do SDK de terceiros implementado pelo adaptador. Neste exemplo, o SDK de amostra tem um SampleInterstitialAdDelegate com callbacks relevantes:

Swift

func interstitialDidLoad(_ interstitial: SampleInterstitial) {
  if let handler = completionHandler {
    delegate = handler(self, nil)
  }
}

func interstitial(
  _ interstitial: SampleInterstitial,
  didFailToLoadAdWith errorCode: SampleErrorCode
) {
  let error =
    SampleCustomEventUtilsSwift.SampleCustomEventErrorWithCodeAndDescription(
      code: SampleCustomEventErrorCodeSwift
        .SampleCustomEventErrorAdLoadFailureCallback,
      description:
        "Sample SDK returned an ad load failure callback with error code: \(errorCode)"
    )
  if let handler = completionHandler {
    delegate = handler(nil, error)
  }
}

Objective-C

- (void)interstitialDidLoad:(SampleInterstitial *)interstitial {
  _adEventDelegate = _loadCompletionHandler(self, nil);
}

- (void)interstitial:(SampleInterstitial *)interstitial
    didFailToLoadAdWithErrorCode:(SampleErrorCode)errorCode {
  NSError *error = SampleCustomEventErrorWithCodeAndDescription(
      SampleCustomEventErrorAdLoadFailureCallback,
      [NSString stringWithFormat:@"Sample SDK returned an ad load failure "
                                 @"callback with error code: %@",
                                 errorCode]);
  _adEventDelegate = _loadCompletionHandler(nil, error);
}

GADMediationInterstitialAd requer a implementação de um método present para mostrar o anúncio:

Swift

func present(from viewController: UIViewController) {
  if let interstitial = interstitial, interstitial.isInterstitialLoaded {
    interstitial.show()
  }
}

Objective-C

- (void)presentFromViewController:(UIViewController *)viewController {
  if ([_interstitialAd isInterstitialLoaded]) {
    [_interstitialAd show];
  } else {
    NSError *error = SampleCustomEventErrorWithCodeAndDescription(
        SampleCustomEventErrorAdNotLoaded,
        [NSString stringWithFormat:@"The interstitial ad failed to present "
                                   @"because the ad was not loaded."]);
    [_adEventDelegate didFailToPresentWithError:error]
  }
}

Encaminhar eventos de mediação ao SDK dos anúncios para dispositivos móveis do Google

Depois de chamar GADMediationInterstitialLoadCompletionHandler com um anúncio carregado, o objeto delegado GADMediationInterstitialAdEventDelegate retornado pode ser usado pelo adaptador para encaminhar eventos de apresentação do SDK de terceiros ao SDK dos anúncios para dispositivos móveis do Google. A classe SampleCustomEventInterstitial implementa o protocolo SampleInterstitialAdDelegate para encaminhar callbacks da rede de publicidade de amostra ao SDK dos anúncios para dispositivos móveis do Google.

É importante que seu evento personalizado encaminhe o maior número possível desses callbacks para que seu app receba esses eventos equivalentes do SDK dos anúncios para dispositivos móveis do Google. Confira um exemplo de como usar callbacks:

Swift

func interstitialWillPresentScreen(_ interstitial: SampleInterstitial) {
  delegate?.willPresentFullScreenView()
  delegate?.reportImpression()
}

func interstitialWillDismissScreen(_ interstitial: SampleInterstitial) {
  delegate?.willDismissFullScreenView()
}

func interstitialDidDismissScreen(_ interstitial: SampleInterstitial) {
  delegate?.didDismissFullScreenView()
}

func interstitialWillLeaveApplication(_ interstitial: SampleInterstitial) {
  delegate?.reportClick()
}

Objective-C

- (void)interstitialWillPresentScreen:(SampleInterstitial *)interstitial {
  [_adEventDelegate willPresentFullScreenView];
  [_adEventDelegate reportImpression];
}

- (void)interstitialWillDismissScreen:(SampleInterstitial *)interstitial {
  [_adEventDelegate willDismissFullScreenView];
}

- (void)interstitialDidDismissScreen:(SampleInterstitial *)interstitial {
  [_adEventDelegate didDismissFullScreenView];
}

- (void)interstitialWillLeaveApplication:(SampleInterstitial *)interstitial {
  [_adEventDelegate reportClick];
}

Isto conclui a implementação dos eventos personalizados para anúncios intersticiais. O exemplo completo está disponível no GitHub. É possível usá-lo com uma rede de publicidade que já é compatível ou modificá-lo para exibir anúncios intersticiais de eventos personalizados.