Eventi personalizzati degli annunci con premio

Prerequisiti

Completa la configurazione degli eventi personalizzati.

Richiedere un annuncio con premio

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

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

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

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, GADMediationAdapter {

  fileprivate var rewardedAd: SampleCustomEventRewarded?
  ...

  func loadRewarded(
    for adConfiguration: GADMediationRewardedAdConfiguration,
    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 in corso...

  • Implementazione della GADMediationRewardedAd 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 SampleCustomEventRewarded: NSObject, GADMediationRewardedAd {
  /// The Sample Ad Network rewarded ad.
  var nativeAd: SampleRewarded?

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

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

  func loadRewarded(
    for adConfiguration: GADMediationRewardedAdConfiguration,
    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 the 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];
}

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

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 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

Dopo aver 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 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 rewardedAdDidPresent(_ rewarded: SampleRewardedAd) {
  delegate?.willPresentFullScreenVideo()
  delegate?.didStartVideo()
}

func rewardedAdUserDidEarnReward(_ rewarded: SampleRewardedAd) {
  GADAdReward aReward = GADAdReward("", 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];
}

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 oppure puoi modificarlo per mostrare annunci con premio di eventi personalizzati.