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,
viene chiamato il metodo loadBanner:adConfiguration:completionHandler: sul
nome della classe fornito durante la creazione di un evento
personalizzato. In questo caso,
il metodo si trova in SampleCustomEvent, che a sua volta chiama
il metodo loadBanner:adConfiguration:completionHandler: 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: in questa classe. Inoltre, crea una
nuova classe per implementare GADMediationBannerAd.
Nel nostro esempio di evento personalizzato,
SampleCustomEvent implementa
l'interfaccia GADMediationAdapter e poi delega a
SampleCustomEventBanner.
Swift
import GoogleMobileAds class SampleCustomEvent: NSObject, MediationAdapter { fileprivate var bannerAd: SampleCustomEventBanner? ... func loadBanner( for adConfiguration: MediationBannerAdConfiguration, 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 un
GADMediationBannerLoadCompletionHandlermetodo al termine del caricamento.Implementare il protocollo
GADMediationBannerAd.Ricezione e segnalazione dei callback degli eventi dell'annuncio a Google Mobile Ads SDK.
Il parametro facoltativo definito nell'interfaccia utente 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 durante l'istanza di un oggetto annuncio.
Swift
class SampleCustomEventBanner: NSObject, MediationBannerAd { /// The Sample Ad Network banner ad. var bannerAd: SampleBanner? /// The ad event delegate to forward ad rendering events to Google Mobile Ads SDK. var delegate: MediationBannerAdEventDelegate? /// Completion handler called after ad load var completionHandler: GADMediationBannerLoadCompletionHandler? func loadBanner( for adConfiguration: MediationBannerAdConfiguration, 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]; }
Indipendentemente dal fatto che l'annuncio venga recuperato correttamente o che si verifichi un errore, devi chiamare GADMediationBannerLoadCompletionHandler. In caso di esito positivo, passa la classe che implementa GADMediationBannerAd con un valore nil per il parametro di errore; in caso di errore, 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 SampleBannerAdDelegate con i 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 a Google Mobile Ads SDK
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 a
Google Mobile Ads SDK. La classe SampleCustomEventBanner implementa il
SampleBannerAdDelegate protocollo per inoltrare i callback dalla rete pubblicitaria di esempio
a Google Mobile Ads SDK.
È importante che l'evento personalizzato inoltri il maggior numero possibile di questi callback, in modo che l'app riceva questi eventi equivalenti da Google Mobile Ads SDK. Ecco un esempio di utilizzo dei callback:
Swift
func bannerWillLeaveApplication(_ banner: SampleBanner) { delegate?.reportClick() }
Objective-C
- (void)bannerWillLeaveApplication:(SampleBanner *)banner { [_adEventDelegate reportClick]; }
In questo modo si completa l'implementazione degli eventi personalizzati per gli annunci banner. L'esempio completo è disponibile su GitHub. Puoi utilizzarlo con una rete pubblicitaria già supportata o modificarlo per visualizzare gli annunci banner di eventi personalizzati.