Eventi personalizzati degli annunci banner

Prerequisiti

Completa la configurazione degli eventi personalizzati.

Richiedere un annuncio banner

Quando l'elemento pubblicitario dell'evento personalizzato viene raggiunto nella catena di mediazione a cascata,the loadBanner: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 loadBanner:adConfiguration:completionHandler: method in SampleCustomEventBanner.

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

Nel nostro esempio di evento personalizzato, SampleCustomEvent implementathe GADMediationAdapter interface e poi delega aSampleCustomEventBanner.

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 è responsabile delle seguenti attività:

  • Caricare l'annuncio banner e richiamare GADMediationBannerLoadCompletionHandler method al termine del caricamento

  • Implementazione della GADMediationBannerAd 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

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

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

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 SampleBannerAdDelegate con callback pertinenti:

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 richiede l'implementazione di una proprietà UIView:

Swift

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

Objective-C

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

Inoltrare gli eventi di mediazione all'SDK Google Mobile Ads

Dopo aver chiamato GADMediationBannerLoadCompletionHandler con un annuncio caricato, l'oggetto delegato GADMediationBannerAdEventDelegate restituito può essere utilizzato dall'adattatore per inoltrare gli eventi di presentazione dall'SDK di terze parti all'SDK Google Mobile Ads. La classe SampleCustomEventBanner implementa il protocollo SampleBannerAdDelegate 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 bannerWillLeaveApplication(_ banner: SampleBanner) {
  delegate?.reportClick()
}

Objective-C

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

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