必要條件
完成自訂事件設定。
要求原生廣告
在瀑布式中介鏈中到達自訂事件明細項目時,系統會根據您在建立自訂事件時提供的類別名稱,呼叫 loadNativeAd:adConfiguration:completionHandler:
方法。在本例中,該方法位於 SampleCustomEvent
中,然後會在 SampleCustomEventNative
中呼叫 loadNativeAd:adConfiguration:completionHandler:
方法。
如要要求原生廣告,請建立或修改實作 GADMediationAdapter
和 loadNativeAd:adConfiguration:completionHandler:
的類別。如果
已有擴充 GADMediationAdapter
的類別
有loadNativeAd:adConfiguration:completionHandler:
。此外,請建立新類別來實作 GADMediationNativeAd
。
以這個自訂事件為例
SampleCustomEvent
導入
GADMediationAdapter
介面,然後委派給
SampleCustomEventNative
。
Swift
import GoogleMobileAds class SampleCustomEvent: NSObject, GADMediationAdapter { fileprivate var nativeAd: SampleCustomEventNativeAd? func loadNativeAd( for adConfiguration: GADMediationNativeAdConfiguration, 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` 負責執行下列工作:
載入原生廣告
實作
GADMediationNativeAd
通訊協定。接收並回報廣告事件回呼至 Google Mobile Ads SDK
廣告設定中包含 Ad Manager 使用者介面中定義的選用參數。參數可以透過
adConfiguration.credentials.settings[@"parameter"]
。這個參數是
通常是廣告聯播網 SDK 要求的廣告單元 ID
建立廣告物件的例項。
Swift
class SampleCustomEventNativeAd: NSObject, GADMediationNativeAd { /// 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: GADMediationNativeAdEventDelegate? /// Completion handler called after ad load var completionHandler: GADMediationNativeLoadCompletionHandler? func loadNativeAd( for adConfiguration: GADMediationNativeAdConfiguration, 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: GADAdLoaderOptions in options { if let imageOptions = loaderOptions as? GADNativeAdImageAdLoaderOptions { 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? GADNativeAdMediaAdLoaderOptions { switch mediaOptions.mediaAspectRatio { case GADMediaAspectRatio.landscape: sampleRequest.preferredImageOrientation = NativeAdImageOrientation.landscape case GADMediaAspectRatio.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]; }
無論廣告是否成功擷取或發生錯誤,您都會呼叫 GADMediationNativeAdLoadCompletionHandler
。如果成功,請傳遞實作 GADMediationNativeAd
的類別,並為錯誤參數使用 nil
值;如果失敗,請傳遞遇到的錯誤。
通常,這些方法是在來自
您的轉接程式導入的第三方 SDK。在本例中,Sample SDK 有 SampleNativeAdDelegate
和相關的回呼:
Swift
func adLoader( _ adLoader: SampleNativeAdLoader, didReceive nativeAd: SampleNativeAd ) { extraAssets = [ SampleCustomEventConstantsSwift.awesomenessKey: nativeAd.degreeOfAwesomeness ?? "" ] if let image = nativeAd.image { images = [GADNativeAdImage(image: image)] } else { let imageUrl = URL(fileURLWithPath: nativeAd.imageURL) images = [GADNativeAdImage(url: imageUrl, scale: nativeAd.imageScale)] } if let mappedIcon = nativeAd.icon { icon = GADNativeAdImage(image: mappedIcon) } else { let iconURL = URL(fileURLWithPath: nativeAd.iconURL) icon = GADNativeAdImage(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); }
地圖原生廣告
不同的 SDK 都有各自獨特的原生廣告格式。一張圖片可能會回傳 包含「title」標籤的物件例如另一個欄位 「headline」。此外,我們還提供追蹤曝光及處理流程的方法 每個 SDK 的點擊都不相同。
為解決這些問題,當自訂事件從中介 SDK 接收原生廣告物件時,應使用實作 GADMediationNativeAd
的類別 (例如 SampleCustomEventNativeAd
) 來「對應」中介 SDK 的原生廣告物件,以便符合 Google Mobile Ads SDK 預期的介面。
接下來,我們將進一步探討 SampleCustomEventNativeAd
的實作詳細資料。
儲存對應項目
GADMediationNativeAd
應實作以下
對應自其他 SDK 的資源:
Swift
var nativeAd: SampleNativeAd? var headline: String? { return nativeAd?.headline } var images: [GADNativeAdImage]? var body: String? { return nativeAd?.body } var icon: GADNativeAdImage? 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; }
部分中介網路可能會提供超出
Google Mobile Ads SDK。GADMediationNativeAd
通訊協定包含名為 extraAssets
的方法,Google Mobile Ads SDK 會使用這項方法,從對應器中擷取任何「額外」資產。
地圖圖片素材資源
對應圖片素材資源比對應簡單的資料更複雜
類型,例如 NSString
或 double
Google 可能會自動下載圖片,或
以網址值的形式傳回螢幕的像素密度也可能不同。
為協助您管理這些詳細資料,Google Mobile Ads SDK 提供
GADNativeAdImage
類別。圖片素材資源資訊 (無論是實際的 UIImage
物件或僅為 NSURL
值) 都應使用此類別傳回至 Google Mobile Ads SDK。
以下為對應工具類別處理建立 GADNativeAdImage
來存放
圖示圖片:
Swift
if let image = nativeAd.image { images = [GADNativeAdImage(image: image)] } else { let imageUrl = URL(fileURLWithPath: nativeAd.imageURL) images = [GADNativeAdImage(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] ]; }
曝光和點擊事件
Google Mobile Ads SDK 和中介服務的 SDK 需要知道 但只需要一個 SDK 追蹤這些事件自訂事件可採用兩種不同的方法,這取決於中介 SDK 是否支援追蹤曝光和點擊。
使用 Google Mobile Ads SDK 追蹤點擊和曝光
如果中介服務的 SDK 不會自行執行曝光和點擊追蹤,
提供了記錄點擊和曝光的方法,Google Mobile Ads SDK 可以
追蹤這些事件並通知轉接程式。GADMediationNativeAd
通訊協定包含兩個方法:didRecordImpression:
和 didRecordClickOnAssetWithName:view:viewController:
,自訂事件可實作這兩個方法,以便在經仲介的原生廣告物件上呼叫對應的方法:
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]; } }
實作 GADMediationNativeAd
通訊協定的類別會保留對範例 SDK 原生廣告物件參照,因此可以對該物件呼叫適當的方法,以便回報點擊或曝光。請注意,didRecordClickOnAssetWithName:view:viewController:
方法會採用單一參數:與收到點擊的本機廣告素材資源相對應的 View
物件。
使用中介服務的 SDK 追蹤點擊和曝光次數
部分中介 SDK 可能會自行追蹤點擊和曝光。在這種情況下,您應實作 handlesUserClicks
和 handlesUserImpressions
方法,如以下程式碼片段所示。退貨
YES
,表示自訂事件負責追蹤
並且會在這些事件發生時通知 Google Mobile Ads SDK。
覆寫點擊和曝光追蹤的自訂事件可以使用
將原生廣告的檢視畫面傳遞至中介服務 SDK 的 didRenderInView:
訊息
以便中介服務 SDK 進行實際追蹤。自訂事件範例專案 (本指南的程式碼片段取自該專案) 中的範例 SDK 不會使用這種方法,但如果使用這種方法,自訂事件程式碼會呼叫 setNativeAdView:view:
方法,如以下程式碼片段所示:
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]; }
將中介服務事件轉送至 Google Mobile Ads SDK
呼叫完畢後
GADMediationNativeLoadCompletionHandler
載入的廣告,這時傳回的 GADMediationNativeAdEventDelegate
張委派代表
即可讓轉接程式使用從
第三方 SDK 整合 Google Mobile Ads SDK。
請務必盡可能轉寄這些回呼,讓應用程式從 Google Mobile Ads SDK 接收這些對等事件。以下是回呼的使用範例:
這就完成原生廣告的自訂事件導入作業。完整範例 會在 GitHub。