原生進階

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

原生廣告載入時,應用程式會透過其中一個 GADAdLoaderDelegate 通訊協定訊息。這樣一來,您的應用程式就會 (但不一定要立即進行)。 為了輕鬆顯示系統定義的廣告格式,SDK 提供了實用的 再複習一下,機構節點 是所有 Google Cloud Platform 資源的根節點

GADNativeAdView

GADNativeAd 有一個對應的「廣告瀏覽」 類別: GADNativeAdView。 這個廣告檢視類別是發布商用來顯示廣告的 UIView。 例如,單一 GADNativeAdView 可顯示單一執行個體的 GADNativeAd。每個 UIView 物件,用來顯示該廣告 資產應為該 GADNativeAdView 物件的子視圖。

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

GADNativeAdView 類別也提供用於註冊的 IBOutlets 每個資產使用的檢視畫面,以及註冊 GADNativeAd敬上 物件本身以這種方式註冊檢視畫面,SDK 會自動 處理以下工作:

  • 正在記錄點擊次數。
  • 記錄曝光 (螢幕第一個像素顯示時)。
  • 顯示 AdChoices 重疊廣告。

AdChoices 重疊元素

間接原生廣告 (透過 Ad Manager放送) 候補廣告或透過 Ad Exchange 或 AdSense),在 AdChoices 廣告標籤中加入「廣告」元素時, SDK。 請保留您偏好的空間 角落 自動插入的 AdChoices 標誌。此外,請 確認 AdChoices 重疊元素放在允許圖示顯示的內容中 。 如要進一步瞭解疊加層的外觀和功能,請參閱 程式輔助原生廣告導入指南

程式輔助原生廣告的廣告歸因

顯示程式輔助原生廣告時,您必須註明廣告標示: 表示此檢視畫面為廣告。 請參閱這個頁面查看政策規範。

程式碼範例

我們來看看如何透過動態載入的檢視畫面顯示原生廣告 從 xib 檔案中在使用 GADAdLoaders 時,這可以派上用場 以便請求多種格式

設計 UIView

第一步是設定可顯示原生廣告素材資源的 UIViews。 您可以按照在 Interface Builder 中進行這項操作,就像建立任何其他函式時一樣 xib 檔案。以下是原生廣告的版面配置 廣告看起來可能:

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

GADNativeAdView。 這是用來顯示 GADNativeAd 的廣告檢視類別。

您也需為 GADMediaView 設定自訂類別,而該類別會使用 顯示廣告的影片或圖片。

設定完畢後,您為廣告瀏覽類別指派了正確的廣告檢視類別 將廣告檢視畫面的素材資源位置連結至您建立的 UIViews。 以下說明如何將廣告檢視畫面的素材資源位置連結至已建立的 UIViews 的廣告:

GADNativeAdView的插座已連結到插座面板上 在介面建構工具中版面配置的 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)")
  }
}

建立 UIViewRepresentationable

撰寫 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 guaranteed to be 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。

Swift 自訂轉譯範例 SwiftUI 原生廣告範例 Objective-C 自訂顯示範例

GADMediaView

圖片和影片素材資源是透過以下方式向使用者顯示: GADMediaView。 這是可在 xib 檔案中定義,或以動態方式建構的 UIView。 應放在 GADNativeAdView 的檢視區塊階層內,如: 或觀看任何其他資產檢視畫面。

和所有素材資源檢視畫面一樣,媒體檢視畫面也必須包含其內容 。系統是透過 mediaContent敬上 「GADMediaView」上屬性。 mediaContent 屬性 GADNativeAd。 包含的媒體內容,可以傳遞至 GADMediaView

以下是 Google 搜尋的 自訂轉譯範例 (Swift |Objective-C) 說明如何在 GADMediaView 中填入原生廣告素材資源 GADMediaContent (來自 GADNativeAd):

Swift

nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

Objective-C

nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

確認原生廣告檢視畫面的介面製作工具檔案中, 檢視畫面自訂類別設為 GADMediaView,並將該類別連結至 mediaView的插座。

變更圖片內容模式

GADMediaView 類別會遵循 UIView contentMode敬上 屬性。如果想變更圖片的縮放方式 GADMediaView,設定對應的 UIViewContentMode GADMediaViewcontentMode 屬性上,即可達到此目的。

例如,如要在顯示圖片時填入 GADMediaView (廣告沒有 影片):

Swift

nativeAdView.mediaView?.contentMode = .aspectFill

Objective-C

nativeAdView.mediaView.contentMode = UIViewContentModeAspectFill;

GADMediaContent

GADMediaContent 類別會保留與原生廣告的媒體內容相關的資料,亦即 會透過 GADMediaView 類別顯示。在 GADMediaView 上設定時 mediaContent 屬性:

  • 如果有可用的影片資產,系統會進行緩衝處理,並開始在 GADMediaView。如要確認影片資產是否可用,請查看 hasVideoContent

  • 如果廣告不包含影片素材資源,系統就會下載 mainImage 素材資源 並改為放在 GADMediaView

,瞭解如何調查及移除這項存取權。

後續步驟

進一步瞭解使用者隱私