Eventi personalizzati di annunci con premio

Prerequisiti

Completa la configurazione degli eventi personalizzati.

Richiedere un annuncio con premio

Quando l'elemento pubblicitario evento personalizzato viene raggiunto nella catena di mediazione a cascata, viene chiamato il metodo loadRewarded:adConfiguration:completionHandler: sul nome della classe che hai fornito durante la creazione di un evento personalizzato. In questo caso, il metodo si trova in SampleCustomEvent, che poi chiama il metodo loadRewarded:adConfiguration:completionHandler: in SampleCustomEventRewarded.

Per richiedere un annuncio con premio, crea o modifica una classe che implementi GADMediationAdapter e loadRewarded:adConfiguration:completionHandler:. Se esiste già una classe che estende GADMediationAdapter, implementa loadRewarded:adConfiguration:completionHandler: lì. Inoltre, crea una nuova classe per implementare GADMediationRewardedAd.

Nel nostro esempio di evento personalizzato, SampleCustomEvent implementa l'interfaccia GADMediationAdapter e poi delega a SampleCustomEventRewarded.

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, MediationAdapter {

  fileprivate var rewardedAd: SampleCustomEventRewarded?
  ...

  func loadRewarded(
    for adConfiguration: MediationRewardedAdConfiguration,
    completionHandler: @escaping GADMediationRewardedLoadCompletionHandler
  ) {
    self.rewardedAd = SampleCustomEventRewarded()
    self.rewardedAd?.loadRewarded(
      for: adConfiguration, completionHandler: completionHandler)
  }
}

Objective-C

#import "SampleCustomEvent.h"

@implementation SampleCustomEvent
...

SampleCustomEventRewarded *sampleRewarded;

- (void)loadRewardedForAdConfiguration:
            (GADMediationRewardedAdConfiguration *)adConfiguration
                     completionHandler:
                         (GADMediationRewardedLoadCompletionHandler)
                             completionHandler {
  sampleRewarded = [[SampleCustomEventRewarded alloc] init];
  [sampleRewarded loadRewardedForAdConfiguration:adConfiguration
                               completionHandler:completionHandler];
}

SampleCustomEventRewarded è responsabile delle seguenti attività:

  • Caricamento dell'annuncio con premio.

  • Implementazione del protocollo GADMediationRewardedAd.

  • Ricezione e segnalazione di callback degli eventi pubblicitari all'SDK Google Mobile Ads.

Il parametro facoltativo definito nella UI di AdMob è incluso nella configurazione dell'annuncio. È possibile accedere al parametro tramite adConfiguration.credentials.settings[@"parameter"]. Questo parametro è in genere un identificatore dell'unità pubblicitaria richiesto da un SDK della rete pubblicitaria quando viene creata un'istanza di un oggetto annuncio.

Swift

class SampleCustomEventRewarded: NSObject, MediationRewardedAd {
  /// The Sample Ad Network rewarded ad.
  var nativeAd: SampleRewarded?

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

  /// Completion handler called after ad load.
  var completionHandler: GADMediationRewardedLoadCompletionHandler?

  func loadRewarded(
    for adConfiguration: MediationRewardedAdConfiguration,
    completionHandler: @escaping GADMediationRewardedLoadCompletionHandler
  ) {
    rewarded = SampleRewarded.init(
      adUnitID: adConfiguration.credentials.settings["parameter"] as? String)
    rewarded?.delegate = self
    let adRequest = SampleAdRequest()
    adRequest.testMode = adConfiguration.isTestRequest
    self.completionHandler = completionHandler
    rewarded?.fetchAd(adRequest)
  }
}

Objective-C

#import "SampleCustomEventRewarded.h"

@interface SampleCustomEventRewarded () <SampleRewardedAdDelegate,
                                         GADMediationRewardedAd> {
  /// The sample rewarded ad.
  SampleRewarded *_rewardedAd;

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

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

- (void)loadRewardedAdForAdConfiguration:(GADMediationRewardedAdConfiguration *)adConfiguration
                       completionHandler:
                           (GADMediationRewardedLoadCompletionHandler)completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationRewardedLoadCompletionHandler originalCompletionHandler =
      [completionHandler copy];

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

    id<GADMediationRewardedAdEventDelegate> 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"];
  _rewardedAd = [[SampleRewardedAd alloc] initWithAdUnitID:adUnit];
  _rewardedAd.delegate = self;
  SampleAdRequest *adRequest = [[SampleAdRequest alloc] init];
  adRequest.testMode = adConfiguration.isTestRequest;
  [_rewardedAd fetchAd:adRequest];
}

Indipendentemente dal fatto che l'annuncio venga recuperato correttamente o si verifichi un errore, devi chiamare GADMediationRewardedLoadCompletionHandler. In caso di esito positivo, passa la classe che implementa GADMediationRewardedAd con un valore nil per il parametro di errore; in caso di esito negativo, passa l'errore riscontrato.

In genere, questi metodi vengono implementati all'interno dei callback dell'SDK di terze parti implementato dall'adattatore. Per questo esempio, l'SDK di esempio ha un SampleRewardedAdDelegate con callback pertinenti:

Swift

func rewardedDidLoad(_ interstitial: SampleRewarded) {
  if let handler = completionHandler {
    delegate = handler(self, nil)
  }
}

func rewarded(
  rewarded: SampleRewarded, didFailToLoadAdWith errorCode: SampleErrorCode
) {
  let error =
    SampleCustomEventUtils.SampleCustomEventErrorWithCodeAndDescription(
      code: SampleCustomEventErrorCode
        .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)rewardedDidLoad:(SampleRewarded *)rewarded {
  _adEventDelegate = _loadCompletionHandler(self, nil);
}

- (void)rewarded:(SampleInterstitial *)rewarded
    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);
}

GADMediationrewardedAd richiede l'implementazione di un metodo present(viewController:) per visualizzare l'annuncio:

Swift

func present(from viewController: UIViewController) {
  if let rewarded = rewarded, rewarded.isRewardedLoaded {
    rewarded.show()
  }
}

Objective-C

- (void)presentFromViewController:(UIViewController *)viewController {
  if ([_rewardedAd isRewardedLoaded]) {
    [_rewardedAd show];
  } else {
    NSError *error = SampleCustomEventErrorWithCodeAndDescription(
        SampleCustomEventErrorAdNotLoaded,
        [NSString stringWithFormat:
                      @"The rewarded ad failed to present because the ad was not loaded."]);
    [_adEventDelegate didFailToPresentWithError:error]
  }
}

Inoltrare gli eventi di mediazione all'SDK Google Mobile Ads

Una volta chiamato GADMediationRewardedLoadCompletionHandler con un annuncio caricato, l'oggetto delegato GADMediationRewardedAdEventDelegate restituito può essere utilizzato dall'adattatore per inoltrare gli eventi di presentazione dall'SDK di terze parti all'SDK Google Mobile Ads. La classe SampleCustomEventRewarded implementa il protocollo SampleRewardedAdDelegate per inoltrare i callback dalla rete pubblicitaria di esempio all'SDK Google Mobile Ads.

È importante che il tuo 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 rewardedAdDidPresent(_ rewarded: SampleRewardedAd) {
  delegate?.willPresentFullScreenVideo()
  delegate?.didStartVideo()
}

func rewardedAdUserDidEarnReward(_ rewarded: SampleRewardedAd) {
  AdReward aReward = AdReward("", rewarded)
  delegate.didRewardUser()
}

Objective-C

- (void)rewardedAdDidPresent:(SampleRewardedAd *)rewardedAd {
  [_adEventDelegate willPresentFullScreenView];
  [_adEventDelegate didStartVideo];
}

- (void)rewardedAd:(nonnull SampleRewardedAd *)rewardedAd
    userDidEarnReward:(NSUInteger)reward {
  GADAdReward *aReward = [[GADAdReward alloc]
      initWithRewardType:@""
            rewardAmount:[NSDecimalNumber numberWithUnsignedInt:reward]];
  [_adEventDelegate didRewardUserWithReward];
}

In questo modo, l'implementazione degli eventi personalizzati per gli annunci con premio è completata. L'esempio completo è disponibile su GitHub. Puoi utilizzarlo con una rete pubblicitaria già supportata o modificarlo per mostrare annunci con premio per eventi personalizzati.