É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,the loadInterstitial:adConfiguration:completionHandler: method est appelé sur le nom de classe que vous avez fourni lors de la création d'un événement personnalisé. Dans le cas présent, cette méthode se trouve dans SampleCustomEvent, qui appellethe loadInterstitial:adConfiguration:completionHandler: method 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. Créez également une classe pour implémenter GADMediationInterstitialAd.

Dans notre exemple d'événement personnalisé, SampleCustomEvent implémentethe GADMediationAdapter interface , 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'uneGADMediationInterstitialAdLoadCompletionHandler method une fois le chargement terminé

  • Implémenter GADMediationInterstitialAd protocol

  • Recevoir des rappels d'événements d'annonce et créer des rapports les concernant vers le SDK Google Mobile Ads

Le paramètre facultatif défini dans l'interface utilisateur AdMob est inclus dans la configuration de l'annonce. Ce 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 lors de l'instanciation d'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 ou qu'elle rencontre une erreur, vous devez appeler GADMediationInterstitialLoadCompletionHandler. En cas de réussite, 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 règle générale, ces méthodes sont implémentées dans les rappels du SDK tiers implémenté par votre adaptateur. Pour cet exemple, l'exemple de SDK dispose d'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 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 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 être utilisé par l'adaptateur pour transmettre les événements de présentation du SDK tiers au SDK Google Mobile Ads. La classe SampleCustomEventInterstitial implémente le protocole SampleInterstitialAdDelegate pour transférer les rappels de 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 que possible, afin que votre application reçoive ces événements équivalents de la part 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 maintenant 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énement personnalisé.