Anuncios de banner: Eventos personalizados

Requisitos previos

Completa la configuración de eventos personalizados.

Solicita un anuncio banner

Cuando se alcanza la línea de pedido del evento personalizado en la cadena de mediación en cascada, se llama al método loadBanner:adConfiguration:completionHandler: en la de clase que proporcionaste al crear una evento. En este caso, ese método está en SampleCustomEvent, que luego llama el método loadBanner:adConfiguration:completionHandler: en SampleCustomEventBanner

Para solicitar un anuncio de banner, crea o modifica una clase que implemente GADMediationAdapter y loadBanner:adConfiguration:completionHandler:. Si un que extiende GADMediationAdapter ya existe, implementa loadBanner:adConfiguration:completionHandler:. Además, crea Nueva clase para implementar GADMediationBannerAd.

En nuestro ejemplo de evento personalizado, SampleCustomEvent implementa la interfaz GADMediationAdapter y, luego, delega a SampleCustomEventBanner

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, GADMediationAdapter {

  fileprivate var bannerAd: SampleCustomEventBanner?
  ...

  func loadBanner(
    for adConfiguration: GADMediationBannerAdConfiguration,
    completionHandler: @escaping GADMediationBannerLoadCompletionHandler
  ) {
    self.bannerAd = SampleCustomEventBanner()
    self.bannerAd?.loadBanner(
      for: adConfiguration, completionHandler: completionHandler)
  }
}

Objective-C

#import "SampleCustomEvent.h"

@implementation SampleCustomEvent
...

SampleCustomEventBanner *sampleBanner;

- (void)loadBannerForAdConfiguration:
            (GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)
                                         completionHandler {
  sampleBanner = [[SampleCustomEventBanner alloc] init];
  [sampleBanner loadBannerForAdConfiguration:adConfiguration
                           completionHandler:completionHandler];
}

SampleCustomEventBanner es responsable de las siguientes tareas:

  • Cargar el anuncio de banner e invocar un GADMediationBannerLoadCompletionHandler una vez se completa la carga.

  • Implementar el protocolo GADMediationBannerAd

  • Cómo 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 AdMob 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

class SampleCustomEventBanner: NSObject, GADMediationBannerAd {
  /// The Sample Ad Network banner ad.
  var bannerAd: SampleBanner?

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

  /// Completion handler called after ad load
  var completionHandler: GADMediationBannerLoadCompletionHandler?

  func loadBanner(
    for adConfiguration: GADMediationBannerAdConfiguration,
    completionHandler: @escaping GADMediationBannerLoadCompletionHandler
  ) {
    // Create the bannerView with the appropriate size.
    let adSize = adConfiguration.adSize
    bannerAd = SampleBanner(
      frame: CGRect(x: 0, y: 0, width: adSize.size.width, height: adSize.size.height))
    bannerAd?.delegate = self
    bannerAd?.adUnit = adConfiguration.credentials.settings["parameter"] as? String
    let adRequest = SampleAdRequest()
    adRequest.testMode = adConfiguration.isTestRequest
    self.completionHandler = completionHandler
    bannerAd?.fetchAd(adRequest)
  }
}

Objective-C

#import "SampleCustomEventBanner.h"

@interface SampleCustomEventBanner () <SampleBannerAdDelegate,
                                       GADMediationBannerAd> {
  /// The sample banner ad.
  SampleBanner *_bannerAd;

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

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

@implementation SampleCustomEventBanner

- (void)loadBannerForAdConfiguration:
            (GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)
                                         completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationBannerLoadCompletionHandler originalCompletionHandler =
      [completionHandler copy];

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

    id<GADMediationBannerAdEventDelegate> 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"];
  _bannerAd = [[SampleBanner alloc]
      initWithFrame:CGRectMake(0, 0, adConfiguration.adSize.size.width,
                               adConfiguration.adSize.size.height)];
  _bannerAd.adUnit = adUnit;
  _bannerAd.delegate = self;
  SampleAdRequest *adRequest = [[SampleAdRequest alloc] init];
  adRequest.testMode = adConfiguration.isTestRequest;
  [_bannerAd fetchAd:adRequest];
}

Si el anuncio se recupera correctamente o encuentra un error, llamaría a GADMediationBannerLoadCompletionHandler. En caso de éxito, Pasa la clase que implementa GADMediationBannerAd con un valor nil. para el parámetro de error; en caso de falla, pasa por el error que que se encuentre.

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 SampleBannerAdDelegate con devoluciones de llamada relevantes:

Swift

func bannerDidLoad(_ banner: SampleBanner) {
  if let handler = completionHandler {
    delegate = handler(self, nil)
  }
}

func banner(
  _ banner: SampleBanner, 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)bannerDidLoad:(SampleBanner *)banner {
  _adEventDelegate = _loadCompletionHandler(self, nil);
}

- (void)banner:(SampleBanner *)banner
    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);
}

GADMediationBannerAd requiere la implementación de una propiedad UIView:

Swift

var view: UIView {
  return bannerAd ?? UIView()
}

Objective-C

- (nonnull UIView *)view {
  return _bannerAd;
}

Reenvía eventos de mediación al SDK de anuncios de Google para dispositivos móviles

Después de llamar a GADMediationBannerLoadCompletionHandler con un anuncio cargado, el objeto delegado GADMediationBannerAdEventDelegate que se muestra puede que usa el adaptador para reenviar eventos de presentación del SDK de terceros a el SDK de anuncios de Google para dispositivos móviles. La clase SampleCustomEventBanner implementa Protocolo SampleBannerAdDelegate para reenviar devoluciones de llamada desde el anuncio de ejemplo 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 bannerWillLeaveApplication(_ banner: SampleBanner) {
  delegate?.reportClick()
}

Objective-C

- (void)bannerWillLeaveApplication:(SampleBanner *)banner {
  [_adEventDelegate reportClick];
}

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