Requisitos previos
Completa la configuración de eventos personalizados.
Solicita un anuncio intersticial
Cuando se alcanza el concepto 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 la clase que proporcionaste cuando creaste un evento personalizado. En este caso, ese método se encuentra 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:
Carga el anuncio intersticial y, luego, invoca un método
GADMediationInterstitialAdLoadCompletionHandler
una vez que se completa la carga.Implementa el protocolo
GADMediationInterstitialAd
.Recibir y registrar devoluciones de llamada de eventos de anuncios en el SDK de anuncios de Google para dispositivos móviles
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 bloque de anuncios que requiere un SDK de red publicitaria 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 the 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
. En caso de éxito, pasa la clase que implementa GADMediationInterstitialAd
con un valor nil
para el parámetro de error; en caso de falla, 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 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 implementar 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] } }
Cómo reenviar eventos de mediación al SDK de anuncios de Google para dispositivos móviles
Una vez que hayas llamado a GADMediationInterstitialLoadCompletionHandler
con un anuncio cargado, el adaptador podrá usar el objeto delegado GADMediationInterstitialAdEventDelegate
que se devolvió para reenviar los eventos de presentación del SDK de terceros al SDK de anuncios de Google para dispositivos móviles. La clase SampleCustomEventInterstitial
implementa el protocolo SampleInterstitialAdDelegate
para reenviar devoluciones de llamada de la red de publicidad de ejemplo al SDK de anuncios de Google para dispositivos móviles.
Es importante que tu evento personalizado reenvíe tantas devoluciones de llamada como sea posible para que tu app reciba estos eventos equivalentes del SDK de anuncios de Google para dispositivos móviles. A continuación, se muestra 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]; }
Con esto, se completa la implementación de eventos personalizados para 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.