原生高级广告

展示系统定义的原生广告格式

加载原生广告后,您的应用会通过 GADAdLoaderDelegate 协议消息之一接收原生广告对象。然后,就由您的应用负责展示广告了,尽管不一定要立即展示广告。 为了更轻松地展示系统定义的广告格式,SDK 提供了一些实用资源。

GADNativeAdView

对于 GADNativeAd,有一个对应的“广告视图”类:GADNativeAdView。此广告视图类是 UIView,供发布商用来展示广告。例如,单个 GADNativeAdView 可以展示 GADNativeAd 的单个实例。用于展示该广告素材资源的每个 UIView 对象都应为 GADNativeAdView 对象的子视图。

例如,如果您在 UITableView 中展示广告,则其中一个单元格的视图层次结构可能如下所示:

GADNativeAdView 类还提供了注册每项素材资源所用视图时会用到的 IBOutlets,并提供了一个用于注册 GADNativeAd 对象本身的方法。如果以这种方式注册视图,SDK 就可以自动处理诸如以下任务:

  • 记录点击次数。
  • 记录展示次数(当第一个像素出现在屏幕上时)。
  • 显示广告选择叠加层。

“广告选择”叠加层

对于通过 AdMob 补余广告、Ad Exchange 或 AdSense 投放的非直销原生广告,SDK 会添加一个广告选择叠加层。请在原生广告视图中任选您喜欢的一角留出空间,用于展示自动插入的广告选择徽标。此外,在将广告选择叠加层放置在广告内容上时,请确保该图标不会被遮挡,让用户一眼就能看到。 如需详细了解此叠加层的外观和功能,请参阅程序化原生广告植入指南

广告标示

在展示程序化原生广告时,您必须展示广告标示,以指明该视图是广告。

代码示例

我们来了解一下如何使用从 xib 文件动态加载的视图来展示原生广告。此方法非常适合使用经过配置的 GADAdLoaders 请求多种广告格式的情况。

布置 UIView

第一步是布置展示原生广告素材资源的 UIViews。与创建任何其他 xib 文件时一样,您可以在 Interface Builder 中执行此操作。原生广告的布局方式可能如下所示:

请注意图片右上角的自定义类值。该值设置为

GADNativeAdView。这是用于显示 GADNativeAd 的广告视图类。

此外,您还需要为 GADMediaView 设置自定义类,用于显示广告视频或图片。

在视图设置完毕并已给布局分配适当的广告视图类后,请将广告视图的素材资源输出口与创建的 UIViews 关联起来。以下是将广告视图的素材资源输出口与为广告创建的 UIViews 相关联的方法:

在输出口面板中,GADNativeAdView 中的输出口已与 Interface Builder 中所列的 UIViews 相关联。这使 SDK 可以了解哪个 UIView 显示哪个素材资源。同时请务必注意,这些输出口表示广告中可点击的视图。

展示广告

完成布局并关联输出口后,向应用添加以下代码,以便在加载广告后进行展示:

Swift

// Mark: - GADNativeAdLoaderDelegate
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
  print("Received native ad: \(nativeAd)")
  refreshAdButton.isEnabled = true
  // Create and place ad in view hierarchy.
  let nibView = Bundle.main.loadNibNamed("NativeAdView", owner: nil, options: nil)?.first
  guard let nativeAdView = nibView as? GADNativeAdView else {
    return
  }
  setAdView(nativeAdView)

  // Set ourselves as the native ad delegate to be notified of native ad events.
  nativeAd.delegate = self

  // Populate the native ad view with the native ad assets.
  // The headline and mediaContent are guaranteed to be present in every native ad.
  (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
  nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

  // This app uses a fixed width for the GADMediaView and changes its height to match the aspect
  // ratio of the media it displays.
  if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 {
    let heightConstraint = NSLayoutConstraint(
      item: mediaView,
      attribute: .height,
      relatedBy: .equal,
      toItem: mediaView,
      attribute: .width,
      multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio),
      constant: 0)
    heightConstraint.isActive = true
  }

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
  nativeAdView.bodyView?.isHidden = nativeAd.body == nil

  (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
  nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil

  (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
  nativeAdView.iconView?.isHidden = nativeAd.icon == nil

  (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(
    fromStarRating: nativeAd.starRating)
  nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil

  (nativeAdView.storeView as? UILabel)?.text = nativeAd.store
  nativeAdView.storeView?.isHidden = nativeAd.store == nil

  (nativeAdView.priceView as? UILabel)?.text = nativeAd.price
  nativeAdView.priceView?.isHidden = nativeAd.price == nil

  (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
  nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil

  // For the SDK to process touch events properly, user interaction should be disabled.
  nativeAdView.callToActionView?.isUserInteractionEnabled = false

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  // Note: this should always be done after populating the ad views.
  nativeAdView.nativeAd = nativeAd
}

SwiftUI

创建视图模型

创建一个用于加载原生广告并发布原生广告数据更改的视图模型:

import GoogleMobileAds

class NativeAdViewModel: NSObject, ObservableObject, GADNativeAdLoaderDelegate {
  @Published var nativeAd: GADNativeAd?
  private var adLoader: GADAdLoader!

  func refreshAd() {
    adLoader = GADAdLoader(
      adUnitID: "ca-app-pub-3940256099942544/3986624511",
      // The UIViewController parameter is optional.
      rootViewController: nil,
      adTypes: [.native], options: nil)
    adLoader.delegate = self
    adLoader.load(GADRequest())
  }

  func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
    // Native ad data changes are published to its subscribers.
    self.nativeAd = nativeAd
    nativeAd.delegate = self
  }

  func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
    print("\(adLoader) failed with error: \(error.localizedDescription)")
  }
}

创建 UIViewRepresentable

GADNativeView 创建 UIViewRepresentable,并订阅 ViewModel 类中的数据更改:

private struct NativeAdView: UIViewRepresentable {
  typealias UIViewType = GADNativeAdView

  // Observer to update the UIView when the native ad value changes.
  @ObservedObject var nativeViewModel: NativeAdViewModel

  func makeUIView(context: Context) -> GADNativeAdView {
    return
      Bundle.main.loadNibNamed(
        "NativeAdView",
        owner: nil,
        options: nil)?.first as! GADNativeAdView
  }

  func updateUIView(_ nativeAdView: GADNativeAdView, context: Context) {
    guard let nativeAd = nativeViewModel.nativeAd else { return }

    // Each UI property is configurable using your native ad.
    (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline

    nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

    (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body

    (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image

    (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating)

    (nativeAdView.storeView as? UILabel)?.text = nativeAd.store

    (nativeAdView.priceView as? UILabel)?.text = nativeAd.price

    (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser

    (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)

    // For the SDK to process touch events properly, user interaction should be disabled.
    nativeAdView.callToActionView?.isUserInteractionEnabled = false

    // Associate the native ad view with the native ad object. This is required to make the ad
    // clickable.
    // Note: this should always be done after populating the ad views.
    nativeAdView.nativeAd = nativeAd
  }

将视图添加到视图层次结构

以下代码演示了如何将 UIViewRepresentable 添加到视图层次结构:

struct NativeContentView: View {
  // Single source of truth for the native ad data.
  @StateObject private var nativeViewModel = NativeAdViewModel()

  var body: some View {
    ScrollView {
      VStack(spacing: 20) {
        NativeAdView(nativeViewModel: nativeViewModel)  // Updates when the native ad data changes.
          .frame(minHeight: 300)  // minHeight determined from xib.

Objective-C

#pragma mark GADNativeAdLoaderDelegate implementation

- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeAd:(GADNativeAd *)nativeAd {
  NSLog(@"Received native ad: %@", nativeAd);
  self.refreshButton.enabled = YES;

  // Create and place ad in view hierarchy.
  GADNativeAdView *nativeAdView =
      [[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;
  [self setAdView:nativeAdView];

  // Set the mediaContent on the GADMediaView to populate it with available
  // video/image asset.
  nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

  // Populate the native ad view with the native ad assets.
  // The headline is present in every native ad.
  ((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  ((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
  nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;

  [((UIButton *)nativeAdView.callToActionView)setTitle:nativeAd.callToAction
                                              forState:UIControlStateNormal];
  nativeAdView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

    ((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
  nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;

  ((UIImageView *)nativeAdView.starRatingView).image = [self imageForStars:nativeAd.starRating];
  nativeAdView.starRatingView.hidden = nativeAd.starRating ? NO : YES;

  ((UILabel *)nativeAdView.storeView).text = nativeAd.store;
  nativeAdView.storeView.hidden = nativeAd.store ? NO : YES;

  ((UILabel *)nativeAdView.priceView).text = nativeAd.price;
  nativeAdView.priceView.hidden = nativeAd.price ? NO : YES;

  ((UILabel *)nativeAdView.advertiserView).text = nativeAd.advertiser;
  nativeAdView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  nativeAdView.callToActionView.userInteractionEnabled = NO;

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  nativeAdView.nativeAd = nativeAd;
}

GitHub 上的完整示例

如需查看在 Swift、SwiftUI 和 Objective-C 中集成原生广告的完整示例,请点击相应的 GitHub 链接。

Swift 原生高级广告示例 SwiftUI 原生广告示例 Objective-C 原生高级广告示例

GADMediaView

图片和视频素材资源通过 GADMediaView 向用户展示。这是可在 xib 文件中定义或动态构建的 UIView。像所有其他素材资源视图一样,应该将其放在 GADNativeAdView 的视图层次结构中。

与所有素材资源视图一样,媒体视图需要让其内容得到填充,可以使用 GADMediaView 中的 mediaContent 属性对此进行设置。GADNativeAdmediaContent 属性包含可传递到 GADMediaView 的媒体内容。

以下是原生高级广告的代码段示例 (Swift | Objective-C),该示例展示了如何使用 GADNativeAdGADMediaContent,以原生广告素材资源填充 GADMediaView

Swift

nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

Objective-C

nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

确保在原生广告视图的 Interface Builder 文件中,您已将视图自定义类设置为 GADMediaView,并已将其连接到 mediaView 输出口。

更改图片内容模式

GADMediaView 类在显示图片时遵循 UIView contentMode 属性。如果您想在 GADMediaView 中更改图片的缩放方式,请在 GADMediaViewcontentMode 属性中设置相应的 UIViewContentMode 来达到此目的。

例如,要在图片显示时填充 GADMediaView(广告中不包含视频),请使用以下代码:

Swift

nativeAdView.mediaView?.contentMode = .aspectFill

Objective-C

nativeAdView.mediaView.contentMode = UIViewContentModeAspectFill;

GADMediaContent

GADMediaContent 类包含与原生广告的媒体内容相关的数据,媒体内容则通过 GADMediaView 类展示。在 GADMediaView mediaContent 属性中设置时:

  • 如果广告有视频素材资源可用,则系统会对其进行缓冲,并开始在 GADMediaView 内播放。您可以通过检查 hasVideoContent 来判断是否有视频素材资源可用。

  • 如果广告不包含视频素材资源,则会改为下载 mainImage 素材资源,并将其放置在 GADMediaView 内。

后续步骤

不妨详细了解用户隐私权