Prerequisiti
Completa la configurazione degli eventi personalizzati.
Richiedere un annuncio nativo
Quando viene raggiunta la voce di inventario evento personalizzato nella catena di mediazione con struttura a cascata,
viene chiamato il metodo loadNativeAd:adConfiguration:completionHandler:
sul
nome della classe che hai fornito durante la creazione di un
evento. In questo caso,
il metodo si trova in SampleCustomEvent
, che poi chiama
il metodo loadNativeAd:adConfiguration:completionHandler:
in
SampleCustomEventNative
.
Per richiedere un annuncio nativo, crea o modifica una classe che implementi
GADMediationAdapter
e loadNativeAd:adConfiguration:completionHandler:
. Se
esiste già una classe che estende GADMediationAdapter
, implementa
loadNativeAd:adConfiguration:completionHandler:
lì. Inoltre, crea un
nuovo corso per implementare GADMediationNativeAd
.
Nel nostro esempio di evento personalizzato,
SampleCustomEvent
implementa
l'interfaccia GADMediationAdapter
e poi delega a
SampleCustomEventNative
.
Swift
import GoogleMobileAds class SampleCustomEvent: NSObject, MediationAdapter { fileprivate var nativeAd: SampleCustomEventNativeAd? func loadNativeAd( for adConfiguration: MediationNativeAdConfiguration, completionHandler: @escaping GADMediationNativeAdLoadCompletionHandler ) { self.nativeAd = SampleCustomEventNativeAd() self.nativeAd?.loadNativeAd( for: adConfiguration, completionHandler: completionHandler) } }
Objective-C
#import "SampleCustomEvent.h" @implementation SampleCustomEvent SampleCustomEventNativeAd *sampleNativeAd; - (void)loadNativeAdForAdConfiguration: (GADMediationNativeAdConfiguration *)adConfiguration completionHandler: (GADMediationNativeAdLoadCompletionHandler) completionHandler { sampleNative = [[SampleCustomEventNativeAd alloc] init]; [sampleNative loadNativeAdForAdConfiguration:adConfiguration completionHandler:completionHandler]; }
SampleCustomEventNative` è responsabile delle seguenti attività:
Caricamento dell'annuncio nativo
Implementazione del protocollo
GADMediationNativeAd
.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 SampleCustomEventNativeAd: NSObject, MediationNativeAd { /// The Sample Ad Network native ad. var nativeAd: SampleNativeAd? /// The ad event delegate to forward ad rendering events to the Google Mobile /// Ads SDK. var delegate: MediationNativeAdEventDelegate? /// Completion handler called after ad load var completionHandler: GADMediationNativeLoadCompletionHandler? func loadNativeAd( for adConfiguration: MediationNativeAdConfiguration, completionHandler: @escaping GADMediationNativeLoadCompletionHandler ) { let adLoader = SampleNativeAdLoader() let sampleRequest = SampleNativeAdRequest() // The Google Mobile Ads SDK requires the image assets to be downloaded // automatically unless the publisher specifies otherwise by using the // GADNativeAdImageAdLoaderOptions object's disableImageLoading property. If // your network doesn't have an option like this and instead only ever // returns URLs for images (rather than the images themselves), your adapter // should download image assets on behalf of the publisher. This should be // done after receiving the native ad object from your network's SDK, and // before calling the connector's adapter:didReceiveMediatedNativeAd: method. sampleRequest.shouldDownloadImages = true sampleRequest.preferredImageOrientation = NativeAdImageOrientation.any sampleRequest.shouldRequestMultipleImages = false let options = adConfiguration.options for loaderOptions: AdLoaderOptions in options { if let imageOptions = loaderOptions as? NativeAdImageAdLoaderOptions { sampleRequest.shouldRequestMultipleImages = imageOptions.shouldRequestMultipleImages // If the GADNativeAdImageAdLoaderOptions' disableImageLoading property is // YES, the adapter should send just the URLs for the images. sampleRequest.shouldDownloadImages = !imageOptions.disableImageLoading } else if let mediaOptions = loaderOptions as? NativeAdMediaAdLoaderOptions { switch mediaOptions.mediaAspectRatio { case MediaAspectRatio.landscape: sampleRequest.preferredImageOrientation = NativeAdImageOrientation.landscape case MediaAspectRatio.portrait: sampleRequest.preferredImageOrientation = NativeAdImageOrientation.portrait default: sampleRequest.preferredImageOrientation = NativeAdImageOrientation.any } } } // This custom event uses the server parameter to carry an ad unit ID, which // is the most common use case. adLoader.delegate = self adLoader.adUnitID = adConfiguration.credentials.settings["parameter"] as? String self.completionHandler = completionHandler adLoader.fetchAd(sampleRequest) } }
Objective-C
#import "SampleCustomEventNativeAd.h" @interface SampleCustomEventNativeAd () <SampleNativeAdDelegate, GADMediationNativeAd> { /// The sample native ad. SampleNativeAd *_nativeAd; /// The completion handler to call when the ad loading succeeds or fails. GADMediationNativeLoadCompletionHandler _loadCompletionHandler; /// The ad event delegate to forward ad rendering events to the Google Mobile /// Ads SDK. id<GADMediationNativeAdEventDelegate> _adEventDelegate; } @end - (void)loadNativeAdForAdConfiguration: (GADMediationNativeAdConfiguration *)adConfiguration completionHandler:(GADMediationNativeLoadCompletionHandler) completionHandler { __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT; __block GADMediationNativeLoadCompletionHandler originalCompletionHandler = [completionHandler copy]; _loadCompletionHandler = ^id<GADMediationNativeAdEventDelegate>( _Nullable id<GADMediationNativeAd> ad, NSError *_Nullable error) { // Only allow completion handler to be called once. if (atomic_flag_test_and_set(&completionHandlerCalled)) { return nil; } id<GADMediationNativeAdEventDelegate> 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; }; SampleNativeAdLoader *adLoader = [[SampleNativeAdLoader alloc] init]; SampleNativeAdRequest *sampleRequest = [[SampleNativeAdRequest alloc] init]; // The Google Mobile Ads SDK requires the image assets to be downloaded // automatically unless the publisher specifies otherwise by using the // GADNativeAdImageAdLoaderOptions object's disableImageLoading property. If // your network doesn't have an option like this and instead only ever returns // URLs for images (rather than the images themselves), your adapter should // download image assets on behalf of the publisher. This should be done after // receiving the native ad object from your network's SDK, and before calling // the connector's adapter:didReceiveMediatedNativeAd: method. sampleRequest.shouldDownloadImages = YES; sampleRequest.preferredImageOrientation = NativeAdImageOrientationAny; sampleRequest.shouldRequestMultipleImages = NO; sampleRequest.testMode = adConfiguration.isTestRequest; for (GADAdLoaderOptions *loaderOptions in adConfiguration.options) { if ([loaderOptions isKindOfClass:[GADNativeAdImageAdLoaderOptions class]]) { GADNativeAdImageAdLoaderOptions *imageOptions = (GADNativeAdImageAdLoaderOptions *)loaderOptions; sampleRequest.shouldRequestMultipleImages = imageOptions.shouldRequestMultipleImages; // If the GADNativeAdImageAdLoaderOptions' disableImageLoading property is // YES, the adapter should send just the URLs for the images. sampleRequest.shouldDownloadImages = !imageOptions.disableImageLoading; } else if ([loaderOptions isKindOfClass:[GADNativeAdMediaAdLoaderOptions class]]) { GADNativeAdMediaAdLoaderOptions *mediaOptions = (GADNativeAdMediaAdLoaderOptions *)loaderOptions; switch (mediaOptions.mediaAspectRatio) { case GADMediaAspectRatioLandscape: sampleRequest.preferredImageOrientation = NativeAdImageOrientationLandscape; break; case GADMediaAspectRatioPortrait: sampleRequest.preferredImageOrientation = NativeAdImageOrientationPortrait; break; default: sampleRequest.preferredImageOrientation = NativeAdImageOrientationAny; break; } } else if ([loaderOptions isKindOfClass:[GADNativeAdViewAdOptions class]]) { _nativeAdViewAdOptions = (GADNativeAdViewAdOptions *)loaderOptions; } } // This custom event uses the server parameter to carry an ad unit ID, which // is the most common use case. NSString *adUnit = adConfiguration.credentials.settings[@"parameter"]; adLoader.adUnitID = adUnit; adLoader.delegate = self; [adLoader fetchAd:sampleRequest]; }
Indipendentemente dal fatto che l'annuncio venga recuperato correttamente o si verifichi un errore, devi chiamare GADMediationNativeAdLoadCompletionHandler
. In caso di esito positivo,
trasferisci la classe che implementa GADMediationNativeAd
con un valore nil
per il parametro di errore; in caso di esito negativo, trasferisci 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 SampleNativeAdDelegate
con callback pertinenti:
Swift
func adLoader( _ adLoader: SampleNativeAdLoader, didReceive nativeAd: SampleNativeAd ) { extraAssets = [ SampleCustomEventConstantsSwift.awesomenessKey: nativeAd.degreeOfAwesomeness ?? "" ] if let image = nativeAd.image { images = [NativeAdImage(image: image)] } else { let imageUrl = URL(fileURLWithPath: nativeAd.imageURL) images = [NativeAdImage(url: imageUrl, scale: nativeAd.imageScale)] } if let mappedIcon = nativeAd.icon { icon = NativeAdImage(image: mappedIcon) } else { let iconURL = URL(fileURLWithPath: nativeAd.iconURL) icon = NativeAdImage(url: iconURL, scale: nativeAd.iconScale) } adChoicesView = SampleAdInfoView() self.nativeAd = nativeAd if let handler = completionHandler { delegate = handler(self, nil) } } func adLoader( _ adLoader: SampleNativeAdLoader, 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)adLoader:(SampleNativeAdLoader *)adLoader didReceiveNativeAd:(SampleNativeAd *)nativeAd { if (nativeAd.image) { _images = @[ [[GADNativeAdImage alloc] initWithImage:nativeAd.image] ]; } else { NSURL *imageURL = [[NSURL alloc] initFileURLWithPath:nativeAd.imageURL]; _images = @[ [[GADNativeAdImage alloc] initWithURL:imageURL scale:nativeAd.imageScale] ]; } if (nativeAd.icon) { _icon = [[GADNativeAdImage alloc] initWithImage:nativeAd.icon]; } else { NSURL *iconURL = [[NSURL alloc] initFileURLWithPath:nativeAd.iconURL]; _icon = [[GADNativeAdImage alloc] initWithURL:iconURL scale:nativeAd.iconScale]; } // The sample SDK provides an AdChoices view (SampleAdInfoView). If your SDK // provides image and click through URLs for its AdChoices icon instead of an // actual UIView, the adapter is responsible for downloading the icon image // and creating the AdChoices icon view. _adChoicesView = [[SampleAdInfoView alloc] init]; _nativeAd = nativeAd; _adEventDelegate = _loadCompletionHandler(self, nil); } - (void)adLoader:(SampleNativeAdLoader *)adLoader 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); }
Annunci nativi di Maps
SDK diversi hanno formati unici per gli annunci nativi. Uno potrebbe restituire oggetti che contengono un campo "title", ad esempio, mentre un altro potrebbe avere "headline". Inoltre, i metodi utilizzati per monitorare le impressioni ed elaborare i clic possono variare da un SDK all'altro.
Per risolvere questi problemi, quando un evento personalizzato riceve un oggetto annuncio nativo dal
relativo SDK di mediazione, deve utilizzare una classe che implementa GADMediationNativeAd
,
come SampleCustomEventNativeAd
, per "mappare" l'oggetto annuncio nativo dell'SDK di mediazione
in modo che corrisponda all'interfaccia prevista dall'SDK Google Mobile Ads.
Ora esaminiamo più da vicino i dettagli di implementazione per
SampleCustomEventNativeAd
.
Memorizzare le mappature
GADMediationNativeAd
è tenuto a implementare determinate proprietà mappate dalle proprietà di altri SDK:
Swift
var nativeAd: SampleNativeAd? var headline: String? { return nativeAd?.headline } var images: [NativeAdImage]? var body: String? { return nativeAd?.body } var icon: NativeAdImage? var callToAction: String? { return nativeAd?.callToAction } var starRating: NSDecimalNumber? { return nativeAd?.starRating } var store: String? { return nativeAd?.store } var price: String? { return nativeAd?.price } var advertiser: String? { return nativeAd?.advertiser } var extraAssets: [String: Any]? { return [ SampleCustomEventConstantsSwift.awesomenessKey: nativeAd?.degreeOfAwesomeness ?? "" ] } var adChoicesView: UIView? var mediaView: UIView? { return nativeAd?.mediaView }
Objective-C
/// Used to store the ad's images. In order to implement the /// GADMediationNativeAd protocol, we use this class to return the images /// property. NSArray<GADNativeAdImage *> *_images; /// Used to store the ad's icon. In order to implement the GADMediationNativeAd /// protocol, we use this class to return the icon property. GADNativeAdImage *_icon; /// Used to store the ad's ad choices view. In order to implement the /// GADMediationNativeAd protocol, we use this class to return the adChoicesView /// property. UIView *_adChoicesView; - (nullable NSString *)headline { return _nativeAd.headline; } - (nullable NSArray<GADNativeAdImage *> *)images { return _images; } - (nullable NSString *)body { return _nativeAd.body; } - (nullable GADNativeAdImage *)icon { return _icon; } - (nullable NSString *)callToAction { return _nativeAd.callToAction; } - (nullable NSDecimalNumber *)starRating { return _nativeAd.starRating; } - (nullable NSString *)store { return _nativeAd.store; } - (nullable NSString *)price { return _nativeAd.price; } - (nullable NSString *)advertiser { return _nativeAd.advertiser; } - (nullable NSDictionary<NSString *, id> *)extraAssets { return @{SampleCustomEventExtraKeyAwesomeness : _nativeAd.degreeOfAwesomeness}; } - (nullable UIView *)adChoicesView { return _adChoicesView; } - (nullable UIView *)mediaView { return _nativeAd.mediaView; } - (BOOL)hasVideoContent { return self.mediaView != nil; }
Alcune reti di mediazione possono fornire asset aggiuntivi oltre a quelli definiti dall'SDK Google Mobile Ads. Il protocollo GADMediationNativeAd
include un metodo
chiamato extraAssets
che l'SDK Google Mobile Ads utilizza per recuperare uno qualsiasi di questi asset "extra" dal mapper.
Asset immagine della mappa
La mappatura degli asset immagine è più complicata della mappatura di tipi di dati più semplici come NSString
o double
. Le immagini potrebbero essere scaricate automaticamente o
restituite come valori URL. Anche la densità di pixel può variare.
Per aiutarti a gestire questi dettagli, l'SDK Google Mobile Ads fornisce la classe
GADNativeAdImage
. Le informazioni sugli asset immagine (se si tratta di UIImage
oggetti effettivi o solo di valori NSURL
) devono essere restituite all'SDK Google Mobile Ads
utilizzando questa classe.
Ecco come la classe mapper gestisce la creazione di un GADNativeAdImage
per contenere
l'immagine dell'icona:
Swift
if let image = nativeAd.image { images = [NativeAdImage(image: image)] } else { let imageUrl = URL(fileURLWithPath: nativeAd.imageURL) images = [NativeAdImage(url: imageUrl, scale: nativeAd.imageScale)] }
Objective-C
if (nativeAd.image) { _images = @[ [[GADNativeAdImage alloc] initWithImage:nativeAd.image] ]; } else { NSURL *imageURL = [[NSURL alloc] initFileURLWithPath:nativeAd.imageURL]; _images = @[ [[GADNativeAdImage alloc] initWithURL:imageURL scale:nativeAd.imageScale] ]; }
Eventi impressione e clic
Sia l'SDK Google Mobile Ads sia l'SDK di mediazione devono sapere quando si verifica un'impressione o un clic, ma solo un SDK deve monitorare questi eventi. Esistono due approcci diversi che gli eventi personalizzati possono utilizzare, a seconda che l'SDK di mediazione supporti il monitoraggio delle impressioni e dei clic autonomamente.
Monitorare i clic e le impressioni con l'SDK Google Mobile Ads
Se l'SDK di mediazione non esegue il proprio monitoraggio di impressioni e clic, ma
fornisce metodi per registrare clic e impressioni, l'SDK Google Mobile Ads può
monitorare questi eventi e inviare una notifica all'adattatore. Il protocollo GADMediationNativeAd
include due metodi: didRecordImpression:
e
didRecordClickOnAssetWithName:view:viewController:
che gli eventi personalizzati possono
implementare per chiamare il metodo corrispondente sull'oggetto annuncio nativo con mediazione:
Swift
func didRecordImpression() { nativeAd?.recordImpression() } func didRecordClickOnAsset( withName assetName: GADUnifiedNativeAssetIdentifier, view: UIView, wController: UIViewController ) { nativeAd?.handleClick(on: view) }
Objective-C
- (void)didRecordImpression { if (self.nativeAd) { [self.nativeAd recordImpression]; } } - (void)didRecordClickOnAssetWithName:(GADUnifiedNativeAssetIdentifier)assetName view:(UIView *)view viewController:(UIViewController *)viewController { if (self.nativeAd) { [self.nativeAd handleClickOnView:view]; } }
Poiché la classe che implementa il protocollo GADMediationNativeAd
contiene un riferimento all'oggetto annuncio nativo dell'SDK di esempio, può chiamare il
metodo appropriato su quell'oggetto per registrare un clic o un'impressione. Tieni presente che il metodo
didRecordClickOnAssetWithName:view:viewController:
accetta un solo
parametro: l'oggetto View
corrispondente all'asset dell'annuncio nativo che ha ricevuto
il clic.
Monitorare i clic e le impressioni con l'SDK di mediazione
Alcuni SDK di mediazione potrebbero preferire monitorare autonomamente i clic e le impressioni. In
questo caso, devi implementare i metodi handlesUserClicks
e
handlesUserImpressions
come mostrato nello snippet seguente. Restituendo
YES
, indichi che l'evento personalizzato si assume la responsabilità di monitorare
questi eventi e che invierà una notifica all'SDK Google Mobile Ads quando si verificano.
Gli eventi personalizzati che ignorano il monitoraggio dei clic e delle impressioni possono utilizzare il messaggio
didRenderInView:
per passare la visualizzazione dell'annuncio nativo all'oggetto annuncio nativo dell'SDK di mediazione
per consentire all'SDK di mediazione di eseguire il monitoraggio effettivo. L'SDK di esempio
del nostro progetto di esempio di evento personalizzato (da cui sono stati presi gli snippet di codice di questa guida) non utilizza questo approccio, ma se lo facesse, il codice dell'evento personalizzato
chiamerebbe il metodo setNativeAdView:view:
come mostrato nello snippet seguente:
Swift
func handlesUserClicks() -> Bool { return true } func handlesUserImpressions() -> Bool { return true } func didRender( in view: UIView, clickableAssetViews: [GADNativeAssetIdentifier: UIView], nonclickableAssetViews: [GADNativeAssetIdentifier: UIView], viewController: UIViewController ) { // This method is called when the native ad view is rendered. Here you would pass the UIView // back to the mediated network's SDK. self.nativeAd?.setNativeAdView(view) }
Objective-C
- (BOOL)handlesUserClicks { return YES; } - (BOOL)handlesUserImpressions { return YES; } - (void)didRenderInView:(UIView *)view clickableAssetViews:(NSDictionary<GADNativeAssetIdentifier, UIView *> *) clickableAssetViews nonclickableAssetViews:(NSDictionary<GADNativeAssetIdentifier, UIView *> *) nonclickableAssetViews viewController:(UIViewController *)viewController { // This method is called when the native ad view is rendered. Here you would // pass the UIView back to the mediated network's SDK. Playing video using // SampleNativeAd's playVideo method [_nativeAd setNativeAdView:view]; }
Inoltrare gli eventi di mediazione all'SDK Google Mobile Ads
Dopo aver chiamato
GADMediationNativeLoadCompletionHandler
con un annuncio caricato, l'oggetto delegato GADMediationNativeAdEventDelegate
restituito
può essere utilizzato dall'adattatore per inoltrare gli eventi di presentazione dall'SDK
di terze parti 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:
In questo modo, l'implementazione degli eventi personalizzati per gli annunci nativi è completata. L'esempio completo è disponibile su GitHub.