Eventos personalizados de anuncios intersticiales

Selecciona la plataforma: Android iOS Android (heredado)

Requisitos previos

Completa la configuración de eventos personalizados.

Solicita un anuncio intersticial

Cuando se alcanza la línea de pedido de evento personalizado en la cadena de mediación en cascada, se llama al método loadInterstitial:adConfiguration:completionHandler: en el nombre de clase que proporcionaste cuando creaste un evento personalizado. En este caso, ese método está en SampleCustomEvent, que, luego, llama al método loadInterstitial:adConfiguration:completionHandler: en SampleCustomEventInterstitial.

Para solicitar un anuncio intersticial, crea o modifica una clase que implemente GADMediationAdapter y loadInterstitial:adConfiguration:completionHandler:. Si ya existe una clase que extiende GADMediationAdapter, implementa loadInterstitial:adConfiguration:completionHandler: allí. Además, crea una clase nueva para implementar GADMediationInterstitialAd.

En nuestro ejemplo de evento personalizado, SampleCustomEvent implementa la interfaz GADMediationAdapter y, luego, delega en SampleCustomEventInterstitial.

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, MediationAdapter {

  fileprivate var interstitialAd: SampleCustomEventInterstitial?
  ...

  func loadInterstitial(
    for adConfiguration: MediationInterstitialAdConfiguration,
    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];
}

SampleCustomEventInterstitial es responsable de las siguientes tareas:

  • Cargar el anuncio intersticial y, una vez que se complete la carga, invocar un método GADMediationInterstitialAdLoadCompletionHandler

  • Implementa el protocolo GADMediationInterstitialAd.

  • Recibir devoluciones de llamada de eventos de anuncios y enviarlas a Google Mobile Ads SDK

El parámetro opcional definido en la IU de se incluye en la configuración del anuncio. Se puede acceder al parámetro a través de adConfiguration.credentials.settings[@"parameter"]. Por lo general, este parámetro es un identificador de unidad de anuncios que requiere el SDK de una red de publicidad cuando se crea una instancia de un objeto de anuncio.

Swift

import GoogleMobileAds

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

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

  var completionHandler: GADMediationInterstitialLoadCompletionHandler?

  func loadInterstitial(
    for adConfiguration: MediationInterstitialAdConfiguration,
    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];
}

Ya sea que el anuncio se recupere correctamente o se produzca un error, debes llamar a GADMediationInterstitialLoadCompletionHandler. Si la operación se realiza correctamente, pasa la clase que implementa GADMediationInterstitialAd con un valor nil para el parámetro de error. Si se produce un error, pasa el error que encontraste.

Por lo general, estos métodos se implementan dentro de las devoluciones de llamada del SDK de terceros que implementa tu adaptador. En este ejemplo, el SDK de muestra tiene un SampleInterstitialAdDelegate con devoluciones de llamada pertinentes:

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 requiere que se implemente un método present para mostrar el anuncio:

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

Reenvía eventos de mediación a Google Mobile Ads SDK

Una vez que hayas llamado a GADMediationInterstitialLoadCompletionHandler con un anuncio cargado, el adaptador podrá usar el objeto delegado GADMediationInterstitialAdEventDelegate que se muestra para reenviar eventos de presentación del SDK de terceros a Google Mobile Ads SDK. La clase SampleCustomEventInterstitial implementa el protocolo SampleInterstitialAdDelegate para reenviar devoluciones de llamada de la red de publicidad de ejemplo a Google Mobile Ads SDK.

Es importante que tu evento personalizado reenvíe la mayor cantidad posible de estas devoluciones de llamada para que tu app reciba estos eventos equivalentes de Google Mobile Ads SDK. A continuación, se muestra un ejemplo de uso de devoluciones de llamada:

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

Con esto, se completa la implementación de eventos personalizados para los anuncios intersticiales. El ejemplo completo está disponible en GitHub. Puedes usarlo con una red de publicidad que ya sea compatible o modificarlo para mostrar anuncios intersticiales de eventos personalizados.