原生進階

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

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

GADNativeAdView

對於 GADNativeAd,有對應的「ad view」類別:GADNativeAdView。這個廣告檢視類別是發布商用來顯示廣告的 UIView。舉例來說,單一 GADNativeAdView 可以顯示單一 GADNativeAd 例項。用來顯示該廣告素材資源的每個 UIView 物件,都應為該 GADNativeAdView 物件的子檢視畫面。

舉例來說,如果您在 UITableView 中顯示廣告,其中一個儲存格的檢視階層可能會像這樣:

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

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

AdChoices 重疊廣告

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

廣告標示

顯示程式輔助原生廣告時,您必須顯示廣告標示,以表示該瀏覽為廣告。

程式碼範例

讓我們來看看如何使用從 xib 檔案動態載入的檢視畫面,顯示原生廣告。在使用已設定為要求多種格式的 GADAdLoaders 時,這可能會非常實用。

排版 UIView

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

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

GADNativeAdView:這是用於顯示 GADNativeAd 的廣告檢視畫面類別。

你也必須為 GADMediaView 設定自訂類別,用來顯示廣告的影片或圖片。

將檢視畫面放置到適當位置,並將正確的廣告檢視畫面類別指派給版面配置後,請將廣告檢視畫面的資產輸出連結至您建立的 UIViews。以下說明如何將廣告檢視畫面的素材資源位置,連結至為廣告建立的 UIViews

在「outlet」面板中,GADNativeAdView 中的「outlet」已連結至 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) 的程式碼片段,說明如何使用 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 中。

後續步驟

進一步瞭解使用者隱私權