Événements personnalisés pour les annonces interstitielles

Prérequis

Terminez la configuration des événements personnalisés.

Demander une annonce interstitielle

Lorsque l'élément de campagne d'événement personnalisé est atteint dans la chaîne de médiation en cascade, la méthode loadInterstitial:adConfiguration:completionHandler: est appelée le nom de classe que vous avez indiqué lors de la création d'une l'événement. 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:. En outre, Créez une classe pour implémenter GADMediationInterstitialAd.

Dans notre exemple d'événement personnalisé, Implémentation de SampleCustomEvent l'interface GADMediationAdapter, puis délègue à SampleCustomEventInterstitial

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 est responsable des tâches suivantes:

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

  • Implémenter le protocole GADMediationInterstitialAd

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

Le paramètre facultatif défini dans l'UI est 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 requis par un SDK de réseau publicitaire d'instancier un objet d'annonce.

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

Que l'annonce soit récupérée correctement ou rencontre une erreur, vous appelle GADMediationInterstitialLoadCompletionHandler. En cas de réussissez, transmettez la classe qui implémente GADMediationInterstitialAd. avec une valeur nil pour le paramètre d'erreur ; en cas d'échec, transmettez l'erreur que vous avez rencontrée.

En règle générale, ces méthodes sont implémentées dans des rappels à partir de la méthode par un SDK tiers implémenté par votre adaptateur. Dans cet exemple, l'exemple de SDK comporte un SampleInterstitialAdDelegate avec les rappels appropriés:

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 d'implémenter 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 au SDK Google Mobile Ads

Une fois que vous avez appelé GADMediationInterstitialLoadCompletionHandler avec un l'objet délégué GADMediationInterstitialAdEventDelegate renvoyé peut seront ensuite utilisés par l'adaptateur pour transférer les événements de présentation à partir du serveur vers le SDK Google Mobile Ads. La classe SampleCustomEventInterstitial et implémente le protocole SampleInterstitialAdDelegate pour transférer les rappels l'exemple de réseau publicitaire vers le SDK Google Mobile Ads.

Il est important que votre événement personnalisé transfère autant de rappels afin que votre application reçoive ces événements équivalents SDK 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];
}

Cette opération termine l'implémentation des événements personnalisés pour les annonces interstitielles. L'intégralité exemple est disponible sur GitHub Vous pouvez l'utiliser avec un réseau publicitaire déjà pris en charge ou le modifier pour afficher des annonces interstitielles avec événement personnalisé.