原生進階

選取平台: Android iOS

顯示系統定義的原生廣告格式

載入原生廣告時,應用程式會透過其中一個 GADAdLoaderDelegate 通訊協定訊息接收原生廣告物件。接著,應用程式會負責顯示廣告 (但不必立即顯示)。為方便顯示系統定義的廣告格式,SDK 提供了一些實用資源。

GADNativeAdView

對於 GADNativeAd,有對應的「廣告檢視」類別: GADNativeAdView。 發布商應使用這個廣告檢視區塊類別顯示廣告。UIView舉例來說,單一 GADNativeAdView 可以顯示 GADNativeAd 的單一執行個體。用於顯示該廣告素材資源的每個 UIView 物件,都應是該 GADNativeAdView 物件的子檢視區塊。

舉例來說,如果您在 UITableView 中顯示廣告,其中一個儲存格的檢視區塊階層可能如下所示:

GADNativeAdView 類別也提供 IBOutlets,用於註冊每個個別素材資源所用的檢視區塊,以及註冊 GADNativeAd 物件本身的方法。以這種方式註冊檢視區塊,可讓 SDK 自動處理下列工作:

  • 記錄點擊次數。
  • 記錄曝光次數 (當第一個像素顯示在畫面上時)。
  • 顯示 AdChoices 廣告標籤。

AdChoices 廣告標籤

如果是間接原生廣告 (透過 Ad Manager 候補廣告或 Ad Exchange/AdSense 放送),SDK 會加入 AdChoices 疊加層。在原生廣告檢視畫面偏好的角落保留空間,供系統自動插入 AdChoices 標誌。並確認安插在內容中的 AdChoices 疊加元素清楚且容易辨識。如要進一步瞭解疊加層的外觀和功能,請參閱程式輔助原生廣告導入指南

程式輔助原生廣告的廣告出處

顯示程式輔助原生廣告時,您必須顯示廣告出處,標示該檢視畫面為廣告。 詳情請參閱我們的政策指南

程式碼範例

接下來,我們將說明如何使用從 XIB 檔案動態載入的檢視區塊,顯示原生廣告。如果使用設定為要求多種格式的 GADAdLoaders,這種做法就非常實用。

配置 UIViews

首先,請配置 UIViews,顯示原生廣告素材資源。 您可以在介面建構器中執行這項操作,就像建立任何其他 XIB 檔案一樣。原生廣告的版面配置可能如下:

請注意圖片右上方的「自訂類別」值。已設為

GADNativeAdView。 這是用於顯示 GADNativeAd 的廣告檢視區塊類別。

您也需要為 GADMediaView 設定自訂類別,用於顯示廣告的影片或圖片。

將檢視區塊就位,並為版面配置指派正確的廣告檢視區塊類別後,請將廣告檢視區塊的素材資源插座連結至您建立的 UIViews。以下說明如何將廣告檢視畫面的素材資源輸出內容連結至為廣告建立的素材資源:UIViews

在插座面板中,GADNativeAdView 中的插座已連結至 Interface Builder 中佈局的 UIViews。這可讓 SDK 瞭解哪個 UIView 會顯示哪個素材資源。此外,請務必記住,這些媒體代表廣告中可點選的觀點。

顯示廣告

版面配置完成並連結插座後,請在應用程式中加入下列程式碼,以便在廣告載入後顯示:

Swift

// Mark: - NativeAdLoaderDelegate
func adLoader(_ adLoader: AdLoader, didReceive nativeAd: NativeAd) {
  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? NativeAdView 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 MediaView 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, NativeAdLoaderDelegate {
  @Published var nativeAd: NativeAd?
  private var adLoader: AdLoader!

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

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

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

建立 UIViewRepresentable

建立 NativeViewUIViewRepresentable ,並訂閱 ViewModel 類別中的資料變更:

private struct NativeAdViewContainer: UIViewRepresentable {
  typealias UIViewType = NativeAdView

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

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

  func updateUIView(_ nativeAdView: NativeAdView, 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) {
        // Updates when the native ad data changes.
        NativeAdViewContainer(nativeViewModel: nativeViewModel)
          .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 向使用者顯示圖片和影片素材資源。這是 UIView,可以在 xib 檔案中定義,也可以動態建構。 與任何其他資產檢視區塊一樣,這個檢視區塊應放置在 GADNativeAdView 的檢視區塊階層中。

與所有素材資源檢視畫面一樣,媒體檢視畫面也需要填入內容。這是透過 GADMediaViewmediaContent 屬性設定。GADNativeAdmediaContent 屬性包含可傳遞至 GADMediaView 的媒體內容。

以下是「自訂算繪」範例 (Swift | Objective-C) 的程式碼片段,說明如何使用 GADNativeAd 中的 GADMediaContent,在 GADMediaView 中填入原生廣告素材資源:

Swift

nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

Objective-C

nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

請確認原生廣告檢視區塊的介面建構工具檔案中,檢視區塊的自訂類別已設為 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 內。

後續步驟

進一步瞭解使用者隱私權