Événements personnalisés pour les annonces interstitielles

Prérequis

Configurez les événements personnalisés.

Demander une annonce interstitielle

Lorsque l'élément de ligne d'événement personnalisé est atteint dans la chaîne de médiation en cascade, la méthode loadInterstitial:adConfiguration:completionHandler: est appelée sur le nom de classe que vous avez fourni lors de la création d'un événement personnalisé. Dans ce cas, cette méthode se trouve dans SampleCustomEvent, qui appelle ensuite la méthode loadInterstitial:adConfiguration:completionHandler: dans SampleCustomEventInterstitial.

Pour demander une annonce interstitielle, créez ou modifiez une classe qui implémente GADMediationAdapter et loadInterstitial:adConfiguration:completionHandler:. Si une classe qui étend GADMediationAdapter existe déjà, implémentez loadInterstitial:adConfiguration:completionHandler: à cet endroit. En outre, créez une classe pour implémenter GADMediationInterstitialAd.

Dans notre exemple d'événement personnalisé, SampleCustomEvent implémente l'interface GADMediationAdapter, puis délègue à 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 est responsable des tâches suivantes :

  • Chargement de l'annonce interstitielle et appel d'une méthode GADMediationInterstitialAdLoadCompletionHandler une fois le chargement terminé.

  • Implémenter le protocole GADMediationInterstitialAd.

  • Recevoir et signaler les rappels d'événements d'annonces au SDK Google Mobile Ads

Le paramètre facultatif défini dans l'interface utilisateur est inclus dans la configuration de l'annonce. Le paramètre est accessible via adConfiguration.credentials.settings[@"parameter"]. Ce paramètre est généralement un identifiant de bloc d'annonces qu'un SDK de réseau publicitaire requiert lors de l'instanciation d'un objet d'annonce.

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

Que l'annonce soit récupérée avec succès ou qu'une erreur se produise, vous devez appeler GADMediationInterstitialLoadCompletionHandler. En cas de succès, transmettez la classe qui implémente GADMediationInterstitialAd avec une valeur nil pour le paramètre d'erreur. En cas d'échec, transmettez l'erreur rencontrée.

En général, ces méthodes sont implémentées dans des rappels du SDK tiers que votre adaptateur implémente. Pour cet exemple, le SDK Sample comporte un SampleInterstitialAdDelegate avec des rappels pertinents :

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 nécessite l'implémentation d'une méthode present pour afficher l'annonce :

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

Transférer les événements de médiation vers le SDK Google Mobile Ads

Une fois que vous avez appelé GADMediationInterstitialLoadCompletionHandler avec une annonce chargée, l'objet délégué GADMediationInterstitialAdEventDelegate renvoyé peut ensuite être utilisé par l'adaptateur pour transférer les événements de présentation du SDK tiers vers le SDK Google Mobile Ads. La classe SampleCustomEventInterstitial implémente le protocole SampleInterstitialAdDelegate pour transférer les rappels de l'exemple de réseau publicitaire au SDK Google Mobile Ads.

Il est important que votre événement personnalisé transmette autant de rappels que possible, afin que votre application reçoive ces événements équivalents du SDK Google Mobile Ads. Voici un exemple d'utilisation des rappels :

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'implémentation des événements personnalisés pour les annonces interstitielles est terminée. L'exemple complet est disponible sur GitHub. Vous pouvez l'utiliser avec un réseau publicitaire déjà compatible ou le modifier pour afficher des annonces interstitielles d'événements personnalisés.