原生高级广告

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

加载原生广告后,您的应用会通过 GADAdLoaderDelegate 协议消息。然后,您的应用将负责 展示广告(但不一定要立即执行此操作)。 为了更轻松地展示系统定义的广告格式,SDK 提供了一些实用功能, 资源。

GADNativeAdView

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

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

GADNativeAdView 类还提供了 IBOutlets 用于注册 每个资产使用的视图,以及一个用于注册 GADNativeAd 对象本身。以这种方式注册视图可让 SDK 自动 处理以下任务:

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

“广告选择”叠加层

对于间接销售的原生广告(通过 Ad Manager 投放) 投放补余广告,或者通过 Ad Exchange 或 AdSense 投放)广告, 。 按您的首选语言留下空间 自动插入“广告选择”徽标的原生广告视图。此外, 确保将“广告选择”叠加层放置在允许显示图标的内容上 。 有关叠加层外观和功能的详情,请参见 程序化原生广告植入指南

程序化原生广告的广告标示

在展示程序化原生广告时,您必须展示广告标示 指明该视图是一个通告。 有关详情,请参阅我们的政策指南

代码示例

让我们来看看如何使用动态加载的视图展示原生广告 。在使用 GADAdLoaders 时,这可能是一种非常有用的方法 配置为请求多种格式

布置 UIView

第一步是布置展示原生广告素材资源的 UIViews。 您可以在 Interface Builder 中执行此操作,就像创建其他任何 xib 文件中。下面介绍了 广告的呈现效果:

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

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

创建 UIViewRepresentable GADNativeView,并订阅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 和 访问相应的 GitHub 链接,获取 Objective-C。

Swift 自定义呈现示例 SwiftUI 原生广告示例 Objective-C 自定义渲染示例

GADMediaView

图片和视频素材资源通过 GADMediaView。 这是一个可在 xib 文件中定义或动态构建的 UIView。 它应放在 GADNativeAdView 的视图层次结构中,如同 任何其他素材资源视图

与所有素材资源视图一样,媒体视图也需要有内容 填充。您可以使用 mediaContent 属性位于 GADMediaView 上。通过 mediaContent 属性 GADNativeAd 包含可传递到 GADMediaView

以下是来自 自定义呈现示例 (Swift |Objective-C) 显示如何使用 GADMediaView 来自GADNativeAdGADMediaContent

Swift

nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

Objective-C

nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

在原生广告视图的 Interface Builder 文件中, 视图自定义类设置为 GADMediaView,且您已将其连接到 mediaView插座。

更改图片内容模式

GADMediaView 类遵循 UIView contentMode 属性。如果您想要更改图片的缩放方式 GADMediaView,请设置相应的 UIViewContentMode 来实现此目的。contentModeGADMediaView

例如,要在图片显示时填充 GADMediaView(广告中没有 视频):

Swift

nativeAdView.mediaView?.contentMode = .aspectFill

Objective-C

nativeAdView.mediaView.contentMode = UIViewContentModeAspectFill;

GADMediaContent

GADMediaContent 类包含与原生广告的媒体内容相关的数据,媒体内容是 使用 GADMediaView 类显示。在 GADMediaView 上设置时 mediaContent 属性:

  • 如果有视频素材资源可用,则系统会对其进行缓冲,并开始在 GADMediaView。您可以通过查看 hasVideoContent

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

后续步骤

详细了解用户隐私