Requisitos previos
Completa la configuración de eventos personalizados.
Cómo solicitar un anuncio intersticial
Cuando se alcanza la línea de pedido de evento personalizado en la cadena de mediación en cascada, se llama athe loadInterstitial:adConfiguration:completionHandler:
method en el nombre de clase que proporcionaste cuando creaste un evento personalizado. En este caso, ese método está en SampleCustomEvent
, que luego llama athe loadInterstitial:adConfiguration:completionHandler:
method 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
implementathe GADMediationAdapter
interface y, luego, delega aSampleCustomEventInterstitial
.
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
method una vez que se completa la cargaCómo implementar
GADMediationInterstitialAd
protocolCómo recibir devoluciones de llamadas de eventos de anuncios y generar informes al SDK de anuncios de Google para dispositivos móviles
El parámetro opcional definido en la IU de Ad Manager 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 un SDK de red de publicidad cuando se crea una instancia de 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, deberías llamar a GADMediationInterstitialLoadCompletionHandler
. En caso de tener é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 devoluciones de llamada desde el SDK de terceros que implementa 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 cargado, el adaptador puede usar el objeto delegado GADMediationInterstitialAdEventDelegate
que se muestra para reenviar eventos de presentación del SDK de terceros al SDK de los 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, de modo que tu app reciba estos eventos equivalentes del SDK de anuncios de Google 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]; }
Con esto, se completa la implementación de eventos personalizados para anuncios intersticiales. El ejemplo completo está disponible en GitHub. Puedes usarla con una red de publicidad que ya sea compatible o modificarla para mostrar anuncios intersticiales de eventos personalizados.