Événements personnalisés de bannières

Conditions préalables

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

Demander une bannière

Lorsque l'élément de campagne de l'événement personnalisé est atteint dans la chaîne de médiation en cascade,the loadBanner: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 loadBanner:adConfiguration:completionHandler: method dans SampleCustomEventBanner.

Pour demander une bannière, créez ou modifiez une classe qui implémente GADMediationAdapter et loadBanner:adConfiguration:completionHandler:. Si une classe qui étend GADMediationAdapter existe déjà, implémentez loadBanner:adConfiguration:completionHandler: à cet endroit. Vous devez également créer une classe pour implémenter GADMediationBannerAd.

Dans notre exemple d'événement personnalisé, SampleCustomEvent implémentethe GADMediationAdapter interface , puis délègue àSampleCustomEventBanner.

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, GADMediationAdapter {

  fileprivate var bannerAd: SampleCustomEventBanner?
  ...

  func loadBanner(
    for adConfiguration: GADMediationBannerAdConfiguration,
    completionHandler: @escaping GADMediationBannerLoadCompletionHandler
  ) {
    self.bannerAd = SampleCustomEventBanner()
    self.bannerAd?.loadBanner(
      for: adConfiguration, completionHandler: completionHandler)
  }
}

Objective-C

#import "SampleCustomEvent.h"

@implementation SampleCustomEvent
...

SampleCustomEventBanner *sampleBanner;

- (void)loadBannerForAdConfiguration:
            (GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)
                                         completionHandler {
  sampleBanner = [[SampleCustomEventBanner alloc] init];
  [sampleBanner loadBannerForAdConfiguration:adConfiguration
                           completionHandler:completionHandler];
}

SampleCustomEventBanner est responsable des tâches suivantes:

  • Chargement de la bannière et appel d'uneGADMediationBannerLoadCompletionHandler method une fois le chargement terminé

  • Implémenter GADMediationBannerAd protocol

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

Le paramètre facultatif défini dans l'interface utilisateur Ad Manager est transmis à votre événement personnalisé dans the loadBanner:adConfiguration:completionHandler: method. 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

class SampleCustomEventBanner: NSObject, GADMediationBannerAd {
  /// The Sample Ad Network banner ad.
  var bannerAd: SampleBanner?

  /// The ad event delegate to forward ad rendering events to the Google Mobile Ads SDK.
  var delegate: GADMediationBannerAdEventDelegate?

  /// Completion handler called after ad load
  var completionHandler: GADMediationBannerLoadCompletionHandler?

  func loadBanner(
    for adConfiguration: GADMediationBannerAdConfiguration,
    completionHandler: @escaping GADMediationBannerLoadCompletionHandler
  ) {
    // Create the bannerView with the appropriate size.
    let adSize = adConfiguration.adSize
    bannerAd = SampleBanner(
      frame: CGRect(x: 0, y: 0, width: adSize.size.width, height: adSize.size.height))
    bannerAd?.delegate = self
    bannerAd?.adUnit = adConfiguration.credentials.settings["parameter"] as? String
    let adRequest = SampleAdRequest()
    adRequest.testMode = adConfiguration.isTestRequest
    self.completionHandler = completionHandler
    bannerAd?.fetchAd(adRequest)
  }
}

Objective-C

#import "SampleCustomEventBanner.h"

@interface SampleCustomEventBanner () <SampleBannerAdDelegate,
                                       GADMediationBannerAd> {
  /// The sample banner ad.
  SampleBanner *_bannerAd;

  /// The completion handler to call when the ad loading succeeds or fails.
  GADMediationBannerLoadCompletionHandler _loadCompletionHandler;

  /// The ad event delegate to forward ad rendering events to the Google Mobile
  /// Ads SDK.
  id <GADMediationBannerAdEventDelegate> _adEventDelegate;
}
@end

@implementation SampleCustomEventBanner

- (void)loadBannerForAdConfiguration:
            (GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)
                                         completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationBannerLoadCompletionHandler originalCompletionHandler =
      [completionHandler copy];

  _loadCompletionHandler = ^id<GADMediationBannerAdEventDelegate>(
      _Nullable id<GADMediationBannerAd> ad, NSError *_Nullable error) {
    // Only allow completion handler to be called once.
    if (atomic_flag_test_and_set(&completionHandlerCalled)) {
      return nil;
    }

    id<GADMediationBannerAdEventDelegate> 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"];
  _bannerAd = [[SampleBanner alloc]
      initWithFrame:CGRectMake(0, 0, adConfiguration.adSize.size.width,
                               adConfiguration.adSize.size.height)];
  _bannerAd.adUnit = adUnit;
  _bannerAd.delegate = self;
  SampleAdRequest *adRequest = [[SampleAdRequest alloc] init];
  adRequest.testMode = adConfiguration.isTestRequest;
  [_bannerAd fetchAd:adRequest];
}

Que la récupération de l'annonce réussisse ou qu'une erreur se produise, vous devez appeler GADMediationBannerLoadCompletionHandler. En cas de réussite, transmettez la classe qui implémente GADMediationBannerAd 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, le SDK exemple dispose d'un SampleBannerAdDelegate avec les rappels pertinents:

Swift

func bannerDidLoad(_ banner: SampleBanner) {
  if let handler = completionHandler {
    delegate = handler(self, nil)
  }
}

func banner(
  _ banner: SampleBanner, 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)bannerDidLoad:(SampleBanner *)banner {
  _adEventDelegate = _loadCompletionHandler(self, nil);
}

- (void)banner:(SampleBanner *)banner
    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);
}

GADMediationBannerAd nécessite d'implémenter une propriété UIView:

Swift

var view: UIView {
  return bannerAd ?? UIView()
}

Objective-C

- (nonnull UIView *)view {
  return _bannerAd;
}

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

Une fois que vous avez appelé GADMediationBannerLoadCompletionHandler avec une annonce chargée, l'objet délégué GADMediationBannerAdEventDelegate renvoyé peut ê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 SampleCustomEventBanner implémente le protocole SampleBannerAdDelegate 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 du SDK Google Mobile Ads. Voici un exemple d'utilisation de rappels:

Swift

func bannerWillLeaveApplication(_ banner: SampleBanner) {
  delegate?.reportClick()
}

Objective-C

- (void)bannerWillLeaveApplication:(SampleBanner *)banner {
  [_adEventDelegate reportClick];
}

L'implémentation des événements personnalisés pour les bannières 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 bannières d'événements personnalisés.