Eventos personalizados de anuncios intersticiales

Requisitos previos

Completa la configuración de eventos personalizados.

Solicita un anuncio intersticial

Cuando se alcanza la línea de pedido del 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 al crear una evento. En este caso, ese método está en SampleCustomEvent, que luego llama el 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:. Además: Crea una clase nueva para implementar GADMediationInterstitialAd.

En nuestro ejemplo de evento personalizado, SampleCustomEvent implementa la interfaz GADMediationAdapter y, luego, delega a 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];
}

SampleCustomEventInterstitial es responsable de las siguientes tareas:

  • Cómo cargar el anuncio intersticial e invocar un GADMediationInterstitialAdLoadCompletionHandler una vez que se completa la carga.

  • Implementar el protocolo GADMediationInterstitialAd

  • Recibir e informar devoluciones de llamadas de eventos de anuncios al SDK de anuncios de Google para dispositivos móviles

El parámetro opcional definido en la IU de es incluidas en la configuración del anuncio. Se puede acceder al parámetro adConfiguration.credentials.settings[@"parameter"] Este parámetro es por lo general, es un identificador de unidades de anuncios que requiere un SDK de red de publicidad cuando un objeto de anuncio.

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

Si el anuncio se recupera correctamente o encuentra un error, llamaría a GADMediationInterstitialLoadCompletionHandler. En caso de que ocurra de forma correcta, pasa la clase que implementa GADMediationInterstitialAd con un valor nil para el parámetro de error. en caso de falla, pasar a través del error que encontraste.

Por lo general, estos métodos se implementan dentro de devoluciones de llamada del o SDK de terceros que implemente tu adaptador. Para este ejemplo, el SDK de muestra tiene un SampleInterstitialAdDelegate con devoluciones de llamada 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 requiere la implementación de 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 al SDK de anuncios de Google para dispositivos móviles

Una vez que hayas llamado a GADMediationInterstitialLoadCompletionHandler con un anuncio, el objeto delegado GADMediationInterstitialAdEventDelegate que se muestra puede para que el adaptador lo utilice para reenviar eventos de presentación al SDK de anuncios de Google para dispositivos móviles. La clase SampleCustomEventInterstitial implementa el protocolo SampleInterstitialAdDelegate para reenviar devoluciones de llamada la red de publicidad de muestra al SDK de anuncios de Google para dispositivos móviles.

Es importante que tu evento personalizado reenvíe la mayor cantidad posible de estas devoluciones de llamada posible, de modo que tu app reciba estos eventos equivalentes de la API de Google SDK de anuncios para dispositivos móviles. Este es un ejemplo del 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];
}

Esto completa la implementación de eventos personalizados para los anuncios intersticiales. El valor completo ejemplo está disponible en GitHub: Puedes usarla con una red de publicidad que ya sea compatible o modificarla para que Mostrar anuncios intersticiales de eventos personalizados.