Eventi personalizzati degli annunci interstitial

Prerequisiti

Completa la configurazione degli eventi personalizzati.

Richiedere un annuncio interstitial

Quando l'elemento pubblicitario dell'evento personalizzato viene raggiunto nella catena di mediazione a cascata,the loadInterstitial:adConfiguration:completionHandler: method viene chiamato in base al nome della classe che hai fornito durante la creazione di un evento personalizzato. In questo caso, il metodo è in SampleCustomEvent, che a sua volta chiama the loadInterstitial:adConfiguration:completionHandler: method in SampleCustomEventInterstitial.

Per richiedere un annuncio interstitial, crea o modifica una classe che implementa GADMediationAdapter e loadInterstitial:adConfiguration:completionHandler:. Se esiste già una classe che si estende GADMediationAdapter, implementa loadInterstitial:adConfiguration:completionHandler: lì. Inoltre, crea una nuova classe per implementare GADMediationInterstitialAd.

Nel nostro esempio di evento personalizzato, SampleCustomEvent implementathe GADMediationAdapter interface e poi 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 è responsabile delle seguenti attività:

  • Caricare l'annuncio interstitial e richiamare un GADMediationInterstitialAdLoadCompletionHandler method una volta completato il caricamento

  • Implementazione della GADMediationInterstitialAd protocol

  • Ricevere e generare report sui callback degli eventi annuncio nell'SDK Google Mobile Ads

Il parametro facoltativo definito nell' AdMob interfaccia utente è incluso nella configurazione dell'annuncio. È possibile accedere al parametro tramite adConfiguration.credentials.settings[@"parameter"]. Questo parametro è generalmente un identificatore di unità pubblicitaria richiesto dall'SDK di una rete pubblicitaria per instaurare un oggetto dell'annuncio.

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

Se l'annuncio è stato recuperato correttamente o se si verifica un errore, devi chiamare GADMediationInterstitialLoadCompletionHandler. In caso di esito positivo, trasmetti la classe che implementa GADMediationInterstitialAd con un valore nil per il parametro di errore; in caso di errore, trasmetti l'errore riscontrato.

In genere, questi metodi vengono implementati all'interno dei callback dell'SDK di terze parti implementato dal tuo adattatore. Per questo esempio, l'SDK Sample ha un valore SampleInterstitialAdDelegate con callback pertinenti:

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 richiede l'implementazione di un metodo present per visualizzare l'annuncio:

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

Inoltrare gli eventi di mediazione all'SDK Google Mobile Ads

Dopo aver chiamato GADMediationInterstitialLoadCompletionHandler con un annuncio caricato, l'oggetto delegato GADMediationInterstitialAdEventDelegate restituito può essere utilizzato dall'adattatore per inoltrare gli eventi di presentazione dall'SDK di terze parti all'SDK Google Mobile Ads. La classe SampleCustomEventInterstitial implementa il protocollo SampleInterstitialAdDelegate per inoltrare i callback dalla rete pubblicitaria di esempio all'SDK Google Mobile Ads.

È importante che l'evento personalizzato inoltri il maggior numero possibile di questi callback, in modo che la tua app riceva questi eventi equivalenti dall'SDK Google Mobile Ads. Ecco un esempio di utilizzo dei callback:

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

L'implementazione degli eventi personalizzati per gli annunci interstitial è completata. L'esempio completo è disponibile su GitHub. Puoi utilizzarlo con una rete pubblicitaria già supportata oppure modificarlo per visualizzare annunci interstitial di eventi personalizzati.