只需对代码进行少量更改,您就可以在广告请求中同时使用原生广告和横幅广告。
前提条件
- Google 移动广告 SDK 7.20.0 或更高版本
- 完成入门指南
加载广告
自定义呈现的原生广告通过 GADAdLoader
对象加载。您还可以配置 GADAdLoader
对象,以发出可能会返回横幅广告或原生广告的广告请求。在创建 GADAdLoader
对象时,将 GADAdLoaderAdTypeGAMBanner
添加到 adTypes
数组参数,并添加 GADAdLoaderAdTypeNative
等原生广告类型,可指定横幅广告应与原生广告竞争以满足请求。
Swift
adLoader = GADAdLoader(adUnitID: "/21775744923/example/native-and-banner", rootViewController: self, adTypes: [.native, .gamBanner], options: [... ad loader options objects ...]) adLoader.delegate = self
Objective-C
self.adLoader = [[GADAdLoader alloc] initWithAdUnitID:@"/21775744923/example/native-and-banner" 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: "/21775744923/example/native-and-banner", rootViewController: self, adTypes: [.native, .gamBanner], options: [bannerViewOptions])
Objective-C
GAMBannerViewOptions *bannerViewOptions = [[GAMBannerViewOptions alloc] init]; bannerViewOptions.enableManualImpressions = YES; self.adLoader = [[GADAdLoader alloc] initWithAdUnitID:@"/21775744923/example/native-and-banner" rootViewController:self adTypes:@[ GADAdLoaderAdTypeNative, GADAdLoaderAdTypeGAMBanner ] options:@[ bannerViewOptions ]];
如果横幅广告加载成功,您可以在确定广告已成功返回并展示在界面中时调用 recordManualImpression
,以手动触发展示:
Swift
bannerView.recordImpression()
Objective-C
[self.bannerView recordImpression];