横幅广告

横幅广告是占据应用部分布局的矩形广告。当用户与应用互动时,横幅广告会停留在屏幕上(锚定在屏幕顶部或底部),或在用户滚动时内嵌于内容中。横幅广告可在一段时间后自动刷新。如需了解详情,请参阅横幅广告概览

本指南介绍了如何开始使用锚定自适应横幅广告,这种广告可以根据您指定的广告宽度针对每种设备优化广告尺寸,从而最大限度地提升广告效果。

锚定自适应横幅广告

锚定型自适应横幅广告是固定宽高比广告,而非常规的固定尺寸广告。宽高比与 320x50 行业标准相似。您指定可用的完整宽度后,系统会返回与该宽度相匹配的最佳高度的广告。来自同一设备的请求中的最佳高度不会发生变化,并且在广告刷新时,周围的视图无需移动。

前提条件

务必用测试广告进行测试

在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。否则,可能会导致您的账号被暂停。

对于 iOS 横幅广告,加载测试广告最简便的方法就是使用下面的专用测试广告单元 ID:

/21775744923/example/adaptive-banner

该测试广告单元 ID 已经过专门配置,可确保每个请求返回的都是测试广告。您可以在自己应用的编码、测试和调试过程中随意使用该测试广告单元 ID。只需确保您会在发布应用前用自己的广告单元 ID 替换该测试广告单元 ID 即可。

如需详细了解移动广告 SDK 的测试广告如何运作,请参阅测试广告

创建 GAMBannerView

横幅广告在 GAMBannerView 对象中展示,因此植入横幅广告的第一步是将 GAMBannerView 添加到视图层次结构中。这通常通过编程方式或通过 Interface Builder 完成。

以程序化方式

您也可以直接将 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

Interface Builder

您可以将 GAMBannerView 添加到 storyboard 或 xib 文件中。使用此方法时,请务必仅在横幅上添加位置约束条件。例如,在屏幕底部显示自适应横幅广告时,请将横幅广告视图的底部设为等于底部布局指南的顶部,并将 centerX 约束条件设为等于超视图的 centerX

横幅的广告尺寸仍以编程方式设置:

Swift

bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

Objective-C

self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);

加载广告

GAMBannerView 创建完毕并配置其属性后,就可以加载广告了。可通过对 GAMRequest 对象调用 loadRequest: 来实现:

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 移动广告 SDK 会按照您在 Ad Manager 界面中指定的频率进行刷新。如果您尚未启用刷新,则需要发出新的请求。

广告事件

通过使用 GADBannerViewDelegate,您可以监听各种生命周期事件,例如广告何时关闭、用户何时离开应用等。

注册横幅广告事件

若要注册横幅广告事件,请将 GAMBannerView 上的 delegate 属性设置为实现 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 Demo 应用中横幅代理方法的实现方式,请参阅广告代理示例。

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 上具有同样功能的方法。下表显示了可与 GADBannerViewDelegate 方法同时调用且具有同样功能的 iOS 方法:

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

手动统计展示

对于应在何时记录展示次数,如果您有特殊的条件,可手动向 Ad Manager 发送展示 ping。为此,请在加载广告之前首先启用能够适配手动展示记录的 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>

有关 iOS API Demo 应用中应用事件的实现方式,请参阅 Ad Manager 应用事件示例。

Swift Objective-C

其他资源

GitHub 上的示例

后续步骤

折叠式横幅广告

折叠式横幅广告是一种横幅广告,最初会以较大的叠加层形式展示,并提供一个可将广告收起为较小尺寸的按钮。请考虑使用它进一步优化您的性能。如需了解详情,请参阅可收起的横幅广告

内嵌自适应横幅广告

与锚定自适应横幅广告相比,内嵌自适应横幅广告是一种更大、更高的横幅广告。这种广告的高度可调整,最高可与设备屏幕一样高。对于在可滚动内容中放置横幅广告的应用,建议使用内嵌自适应横幅广告,而不是锚定自适应横幅广告。如需了解详情,请参阅内嵌自适应横幅广告

浏览其他主题