只需对代码进行一些更改,您就可以在广告请求中合并原生广告和横幅广告。
前提条件
- Google 移动广告 SDK 7.20.0 或更高版本
- 通读使用入门指南
加载广告
自定义呈现的原生广告通过 GADAdLoader
对象加载。GADAdLoader
对象也可以配置为发出可以生成横幅广告或原生广告的广告请求。在创建 GADAdLoader
对象时,需要将 GADAdLoaderAdTypeGAMBanner
和原生广告类型(例如 GADAdLoaderAdTypeNative
)添加到 adTypes
数组参数,以指定横幅广告应与原生广告展开竞争以填充该请求。
Swift
adLoader = GADAdLoader(adUnitID: "/6499/example/nativeandbanner", rootViewController: self, adTypes: [.native, .gamBanner], options: [... ad loader options objects ...]) adLoader.delegate = self
Objective-C
self.adLoader = [[GADAdLoader alloc] initWithAdUnitID:@"/6499/example/nativeandbanner" rootViewController:rootViewController adTypes:@[ GADAdLoaderAdTypeNative, GADAdLoaderAdTypeGAMBanner ] options:@[ ... ad loader options objects ... ]]; self.adLoader.delegate = self;
GAMBannerAdLoaderDelegate
通过 GADAdLoader
请求横幅广告时,广告加载器代理必须遵循 GAMBannerAdLoaderDelegate
协议。此协议包括一条在横幅广告加载后发送的消息:
Swift
public func adLoader(_ adLoader: GADAdLoader, didReceive GAMBannerView: GAMBannerView)
Objective-C
- (void)adLoader:(GADAdLoader *)adLoader didReceiveGAMBannerView:(GAMBannerView *)bannerView;
广告加载程序代理还必须通过响应 validBannerSizesForAdLoader
消息来指定应请求哪些横幅广告尺寸,如下所示。
Swift
public func validBannerSizes(for adLoader: GADAdLoader) -> [NSValue] { return [NSValueFromGADAdSize(GADAdSizeBanner), NSValueFromGADAdSize(GADAdSizeMediumRectangle), NSValueFromGADAdSize(GADAdSizeFromCGSize(CGSize(width: 120, height: 20)))] }
Objective-C
- (NSArray*)validBannerSizesForAdLoader:(GADAdLoader *)adLoader { return @[ @(GADAdSizeBanner), @(GADAdSizeMediumRectangle), @(GADAdSizeFromCGSize(CGSizeMake(120, 20))) ]; }
手动统计展示次数
若要对通过 GADAdLoader
加载的横幅广告启用手动展示次数统计,请在初始化 GADAdLoader
时设置 GAMBannerViewOptions
,并将 enableManualImpressions
设置为 YES
。
Swift
let bannerViewOptions = GAMBannerViewOptions() bannerViewOptions.enableManualImpressions = true adLoader = GADAdLoader( adUnitID: "/6499/example/nativeandbanner", rootViewController: self, adTypes: [.native, .gamBanner], options: [bannerViewOptions])
Objective-C
GAMBannerViewOptions *bannerViewOptions = [[GAMBannerViewOptions alloc] init]; bannerViewOptions.enableManualImpressions = YES; self.adLoader = [[GADAdLoader alloc] initWithAdUnitID:@"/6499/example/nativeandbanner" rootViewController:self adTypes:@[ GADAdLoaderAdTypeNative, GADAdLoaderAdTypeGAMBanner ] options:@[ bannerViewOptions ]];
如果横幅广告已加载,您可以在确定广告已成功返回并展示在屏幕上时调用 recordManualImpression
,以手动触发展示:
Swift
bannerView.recordImpression()
Objective-C
[self.bannerView recordImpression];