橫幅廣告

橫幅廣告是佔用部分應用程式版面的矩形廣告。他們 會固定在使用者與應用程式互動時,固定在畫面上顯示 使用者捲動畫面時,螢幕頂端或底部,或是內嵌到內容旁邊。橫幅 廣告會在一段時間後自動重新整理查看橫幅廣告總覽 瞭解詳情

本指南說明如何開始使用錨定廣告 自動調整橫幅廣告 進而盡量提高成效 指定的廣告寬度

錨定自動調整橫幅廣告

錨定自動調整橫幅廣告是固定的顯示比例廣告,而非一般廣告的 固定大小的廣告。長寬比與 320x50 的業界標準相似。一次 您指定可用的完整寬度時,系統會傳回最佳高度的廣告 調整出理想的寬度和高度來自相同請求的理想高度不會改變 而周圍檢視畫面也會隨著廣告重新整理而移動。

必要條件

一律使用測試廣告進行測試

建構及測試應用程式時,請務必使用測試廣告,而非 現場及正式環境廣告否則帳戶可能會遭到停權。

要載入測試廣告,最簡單的方法就是使用我們專屬的 iOS 測試廣告單元 ID 橫幅廣告:

/21775744923/example/adaptive-banner

這項機制經過特別設定,可針對每個請求傳回測試廣告 在您的程式設計、測試和偵錯時,可以免費使用應用程式。只需製作 務必先用廣告單元 ID 取代廣告單元,再發布應用程式。

若要進一步瞭解 Mobile Ads SDK 測試廣告的運作方式,請參閱「測試 Google Ads

建立 GAMBannerView

橫幅廣告會以GAMBannerView顯示 物件,因此整合橫幅廣告的第一步就是加入 GAMBannerView 位於檢視區塊階層中做法通常是以程式輔助的方式 導入這個 API

程式輔助方式

GAMBannerView 也可以直接例項化。 以下範例會建立 GAMBannerView

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()

    let viewWidth = view.frame.inset(by: view.safeAreaInsets).width

    // Here the current interface orientation is used. Use
    // GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth or
    // GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth if you prefer to load an ad of a
    // particular orientation,
    let adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
    bannerView = GAMBannerView(adSize: adaptiveSize)

    addBannerViewToView(bannerView)
  }

  func addBannerViewToView(_ bannerView: GAMBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    // This example doesn't give width or height constraints, as the provided
    // ad size gives the banner an intrinsic content size to size the view.
    view.addConstraints(
      [NSLayoutConstraint(item: bannerView,
                          attribute: .bottom,
                          relatedBy: .equal,
                          toItem: view.safeAreaLayoutGuide,
                          attribute: .bottom,
                          multiplier: 1,
                          constant: 0),
      NSLayoutConstraint(item: bannerView,
                          attribute: .centerX,
                          relatedBy: .equal,
                          toItem: view,
                          attribute: .centerX,
                          multiplier: 1,
                          constant: 0)
      ])
  }
}

SwiftUI

如要使用 GAMBannerView,請建立 UIViewRepresentable

private struct BannerView: UIViewRepresentable {
  let adSize: GADAdSize

  init(_ adSize: GADAdSize) {
    self.adSize = adSize
  }

  func makeUIView(context: Context) -> UIView {
    // Wrap the GADBannerView in a UIView. GADBannerView automatically reloads a new ad when its
    // frame size changes; wrapping in a UIView container insulates the GADBannerView from size
    // changes that impact the view returned from makeUIView.
    let view = UIView()
    view.addSubview(context.coordinator.bannerView)
    return view
  }

  func updateUIView(_ uiView: UIView, context: Context) {
    context.coordinator.bannerView.adSize = adSize
  }

  func makeCoordinator() -> BannerCoordinator {
    return BannerCoordinator(self)
  }

如要管理 GAMBannerView 的初始化和行為,請建立 Coordinator

class BannerCoordinator: NSObject, GADBannerViewDelegate {

  private(set) lazy var bannerView: GADBannerView = {
    let banner = GADBannerView(adSize: parent.adSize)
    banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
    banner.load(GADRequest())
    banner.delegate = self
    return banner
  }()

  let parent: BannerView

  init(_ parent: BannerView) {
    self.parent = parent
  }

如要取得檢視區塊的寬度,請使用 GeometryReader。本課程 針對目前裝置螢幕方向計算適當的廣告大小。 frame 設為根據廣告大小計算得出的高度。

var body: some View {
  GeometryReader { geometry in
    let adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(geometry.size.width)

    VStack {
      Spacer()
      BannerView(adSize)
        .frame(height: adSize.size.height)
    }
  }

Objective-C

請注意,在這種情況下,我們並未提供寬度或高度限制, 提供的廣告大小可提高橫幅廣告的內建內容大小 檢視畫面。

@import GoogleMobileAds;

@interface ViewController ()

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Here safe area is taken into account, hence the view frame is used after the
  // view has been laid out.
  CGRect frame = UIEdgeInsetsInsetRect(self.view.frame, self.view.safeAreaInsets);
  CGFloat viewWidth = frame.size.width;

  // Here the current interface orientation is used. If the ad is being preloaded
  // for a future orientation change or different orientation, the function for the
  // relevant orientation should be used.
  GADAdSize adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);
  // In this case, we instantiate the banner with desired ad size.
  self.bannerView = [[GAMBannerView alloc] initWithAdSize:adaptiveSize];

  [self addBannerViewToView:self.bannerView];
}

- (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  // This example doesn't give width or height constraints, as the provided
  // ad size gives the banner an intrinsic content size to size the view.
  [self.view addConstraints:@[
    [NSLayoutConstraint constraintWithItem:bannerView
                              attribute:NSLayoutAttributeBottom
                              relatedBy:NSLayoutRelationEqual
                                  toItem:self.view.safeAreaLayoutGuide
                              attribute:NSLayoutAttributeBottom
                              multiplier:1
                                constant:0],
    [NSLayoutConstraint constraintWithItem:bannerView
                              attribute:NSLayoutAttributeCenterX
                              relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                              attribute:NSLayoutAttributeCenterX
                              multiplier:1
                                constant:0]
                                ]];
}
@end

介面建構工具

您可以將 GAMBannerView 新增至分鏡腳本或 xib 檔案。使用時 方法,請務必只在橫幅中加入位置限制。例如: 請在畫面底部顯示自動調整橫幅廣告時 設定與底部版面配置指南頂端相同的位置,然後將 centerX敬上 限制條件等於超級視圖的 centerX

橫幅廣告的大小仍會以程式輔助方式設定:

Swift

bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

Objective-C

self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);

載入廣告

設定好 GAMBannerView 及其屬性後 接著要載入廣告方法是在loadRequest: GAMRequest 物件:

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  // Set the ad unit ID and view controller that contains the GAMBannerView.
  bannerView.adUnitID = "/21775744923/example/adaptive-banner"
  bannerView.rootViewController = self

  bannerView.load(GAMRequest())
}

SwiftUI

banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
banner.load(GADRequest())

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  // Set the ad unit ID and view controller that contains the GAMBannerView.
  self.bannerView.adUnitID = @"/21775744923/example/adaptive-banner";
  self.bannerView.rootViewController = self;

  [self.bannerView loadRequest:[GAMRequest request]];
}

GAMRequest 物件代表單一廣告請求,並包含指定目標資訊等屬性。

如果廣告無法載入,只要您已設定廣告單元重新整理,就不需要明確要求另一個廣告;Google Mobile Ads SDK 會遵循您在 Ad Manager 使用者介面中指定的任何重新整理率。如果您尚未啟用重新整理功能,就必須發出新的要求。

廣告事件

使用 GADBannerViewDelegate 即可監聽生命週期事件、 例如廣告關閉或使用者離開應用程式時,就會觸發這些事件。

註冊橫幅廣告事件

如要註冊橫幅廣告事件,請在以下項目中設定 delegate 屬性: GAMBannerView 至實作 GADBannerViewDelegate 通訊協定。一般來說,會導入橫幅廣告的類別 廣告也是委派類別,在這種情況下,delegate 屬性 設為 self

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // ...
    bannerView.delegate = self
  }
}

SwiftUI

banner.delegate = self

Objective-C

@import GoogleMobileAds;

@interface ViewController () <GADBannerViewDelegate>

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

-   (void)viewDidLoad {
  [super viewDidLoad];
  // ...
  self.bannerView.delegate = self;
}

導入橫幅廣告事件

GADBannerViewDelegate 中的每個方法都標示為選用,因此您 只需實作需要的方法即可這個範例將實作每個方法 並將訊息記錄到控制台:

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  print("bannerViewDidReceiveAd")
}

func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
  print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}

func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
  print("bannerViewDidRecordImpression")
}

func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
  print("bannerViewWillPresentScreen")
}

func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
  print("bannerViewWillDIsmissScreen")
}

func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
  print("bannerViewDidDismissScreen")
}

Objective-C

- (void)bannerViewDidReceiveAd:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidReceiveAd");
}

- (void)bannerView:(GADBannerView *)bannerView didFailToReceiveAdWithError:(NSError *)error {
  NSLog(@"bannerView:didFailToReceiveAdWithError: %@", [error localizedDescription]);
}

- (void)bannerViewDidRecordImpression:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidRecordImpression");
}

- (void)bannerViewWillPresentScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewWillPresentScreen");
}

- (void)bannerViewWillDismissScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewWillDismissScreen");
}

- (void)bannerViewDidDismissScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidDismissScreen");
}

請參閱廣告委派代表在 iOS API 試用版應用程式。

Swift Objective-C

用途

以下是這些廣告事件方法的幾個使用範例。

收到廣告後,在檢視區塊階層中加入橫幅廣告

GAMBannerView 新增至 整個畫面的階層結構 (直到接收廣告為止)只要聆聽 為 bannerViewDidReceiveAd: 事件:

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  // Add banner to view and add constraints.
  addBannerViewToView(bannerView)
}

Objective-C

- (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView {
  // Add bannerView to view and add constraints as above.
  [self addBannerViewToView:self.bannerView];
}

將橫幅廣告製作成動畫

您也可以指定使用 bannerViewDidReceiveAd: 事件將橫幅廣告製作成動畫一次 傳回的字串,如以下範例所示:

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  bannerView.alpha = 0
  UIView.animate(withDuration: 1, animations: {
    bannerView.alpha = 1
  })
}

Objective-C

- (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView {
  bannerView.alpha = 0;
  [UIView animateWithDuration:1.0 animations:^{
    bannerView.alpha = 1;
  }];
}

暫停並重新啟用應用程式

GADBannerViewDelegate 通訊協定具有通知事件的方法,例如: 比方說,使用者在點擊之後會看到或關閉重疊廣告。如果您想追蹤這些事件是否由廣告觸發,請註冊這些 GADBannerViewDelegate 方法。

如要擷取所有類型的疊加層呈現或外部瀏覽器叫用 (而非僅擷取來自廣告點擊的疊加層呈現或外部瀏覽器叫用),建議應用程式在 UIViewControllerUIApplication 上監聽等效方法。下表列出了表格 會在 30 天內叫用的對等 iOS 方法 GADBannerViewDelegate 方法:

GADBannerViewDelegate 方法 iOS 方法
bannerViewWillPresentScreen: UIViewController 的 viewWillDisappear:
bannerViewWillDismissScreen: UIViewController 的 viewWillAppear:
bannerViewDidDismissScreen: UIViewController 的 viewDidAppear:

以人工方式計算曝光次數

如果有特殊條件,您可以手動將曝光連線偵測 (ping) 傳送至 Ad Manager 條件。做法是先完成這項操作 在載入廣告前,讓 GAMBannerView 以手動計算曝光:

Swift

bannerView.enableManualImpressions = true

Objective-C

self.bannerView.enableManualImpressions = YES;

確定廣告已成功傳回並顯示在畫面上後,您可以手動觸發曝光:

Swift

bannerView.recordImpression()

Objective-C

[self.bannerView recordImpression];

應用程式事件

應用程式事件可讓您建立可傳送訊息到應用程式程式碼的廣告。 應用程式就能根據這些訊息採取行動。

您可以使用 GADAppEventDelegate 監聽 Ad Manager 專用的應用程式事件。 這些事件可能會在廣告生命週期的任何時間點發生,即使是在 系統會呼叫 GADBannerViewDelegate 物件的 bannerViewDidReceiveAd:

Swift

// Implement your app event within this method. The delegate will be
// notified when the SDK receives an app event message from the ad.

// Called when the banner receives an app event.
optional public func bannerView(_ banner: GAMBannerView,
    didReceiveAppEvent name: String, withInfo info: String?)

Objective-C

// Implement your app event within this method. The delegate will be
// notified when the SDK receives an app event message from the ad.

@optional
// Called when the banner receives an app event.
-   (void)bannerView:(GAMBannerView *)banner
    didReceiveAppEvent:(NSString *)name
              withInfo:(NSString *)info;

可在檢視控制器中實作應用程式事件方法:

Swift

import GoogleMobileAds

class ViewController: UIViewController, GADAppEventDelegate {}

Objective-C

@import GoogleMobileAds;

@interface ViewController : UIViewController <GADAppEventDelegate> {}

@end

請務必先使用 appEventDelegate 屬性設定委派,再進行 請求廣告

Swift

bannerView.appEventDelegate = self

Objective-C

self.bannerView.appEventDelegate = self;

以下範例說明如何藉由 透過應用程式事件指定色彩:

Swift

func bannerView(_ banner: GAMBannerView, didReceiveAppEvent name: String,
    withInfo info: String?) {
  if name == "color" {
    guard let info = info else { return }
    switch info {
    case "green":
      // Set background color to green.
      view.backgroundColor = UIColor.green
    case "blue":
      // Set background color to blue.
      view.backgroundColor = UIColor.blue
    default:
      // Set background color to black.
      view.backgroundColor = UIColor.black
    }
  }
}

Objective-C

- (void)bannerView:(GAMBannerView *)banner
    didReceiveAppEvent:(NSString *)name
              withInfo:(NSString *)info {
  if ([name isEqual:@"color"]) {
    if ([info isEqual:@"green"]) {
      // Set background color to green.
      self.view.backgroundColor = [UIColor greenColor];
    } else if ([info isEqual:@"blue"]) {
      // Set background color to blue.
      self.view.backgroundColor = [UIColor blueColor];
    } else {
      // Set background color to black.
      self.view.backgroundColor = [UIColor blackColor];
    }
  }
}

然後這個對應的廣告素材會將顏色應用程式事件訊息傳送至 appEventDelegate

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

請參閱 Ad Manager 應用程式事件範例,瞭解如何在 iOS API 試用版應用程式。

Swift Objective-C

其他資源

GitHub 上的範例

後續步驟

可收合橫幅廣告

可收合橫幅廣告是一種橫幅廣告,一開始會以較大尺寸呈現 重疊廣告,還有可將廣告收合成較小尺寸的按鈕。建議採用 進一步提升成效詳情請參閱「可收合橫幅廣告」一文。

內嵌自動調整橫幅廣告

與錨定自動調整橫幅廣告相比,內嵌自動調整橫幅廣告較大、尺寸更加大 橫幅廣告它們的高度不一,而且可以和裝置螢幕一樣高。 建議內嵌自動調整橫幅廣告,而非錨定式自動調整橫幅廣告。 應用程式會在可捲動內容中顯示橫幅廣告。請參閱內嵌自動調整資源配置 橫幅廣告 詳細資料。

探索其他主題