横幅广告

横幅广告是在应用布局中占据一处位置的矩形图片或文字广告。用户与应用互动时,这类广告会停留在屏幕上,并且可在一段时间后自动刷新。如果您刚开始接触移动广告,建议从横幅广告着手。

本指南介绍了如何将 AdMob 横幅广告植入到 iOS 应用中。除了代码段和说明之外,本指南还包含有关如何正确调整横幅广告尺寸的信息以及其他资源的链接。

前提条件

务必用测试广告进行测试

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

对于 iOS 横幅广告,最简便的测试广告加载方法是使用下面的专用测试广告单元 ID: ca-app-pub-3940256099942544/2934735716

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

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

创建GADBannerView

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

Interface Builder

像所有典型视图一样,您可以将GADBannerView添加到 storyboard 或 xib 文件中。使用此方法时,请务必添加宽度和高度限制,以匹配您要展示的广告尺寸。例如,当展示 320x50 的横幅广告时,请使用 320 点的宽度限制和 50 点的高度限制。

以编程方式

您也可以直接将GADBannerView实例化。以下示例演示了如何创建GADBannerView,使之与屏幕安全区域的底部中心对齐,并使用 320x50 的横幅广告尺寸:

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  var bannerView: GADBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    
    // In this case, we instantiate the banner with desired ad size.
    bannerView = GADBannerView(adSize: kGADAdSizeBanner)

    addBannerViewToView(bannerView)
  }

  func addBannerViewToView(_ bannerView: GADBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    view.addConstraints(
      [NSLayoutConstraint(item: bannerView,
                          attribute: .bottom,
                          relatedBy: .equal,
                          toItem: bottomLayoutGuide,
                          attribute: .top,
                          multiplier: 1,
                          constant: 0),
       NSLayoutConstraint(item: bannerView,
                          attribute: .centerX,
                          relatedBy: .equal,
                          toItem: view,
                          attribute: .centerX,
                          multiplier: 1,
                          constant: 0)
      ])
   }
   
}

Objective-C

@import GoogleMobileAds;

@interface ViewController ()

@property(nonatomic, strong) GADBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  // In this case, we instantiate the banner with desired ad size.
  self.bannerView = [[GADBannerView alloc]
      initWithAdSize:kGADAdSizeBanner];

  [self addBannerViewToView:self.bannerView];
}

- (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  [self.view addConstraints:@[
    [NSLayoutConstraint constraintWithItem:bannerView
                               attribute:NSLayoutAttributeBottom
                               relatedBy:NSLayoutRelationEqual
                                  toItem:self.bottomLayoutGuide
                               attribute:NSLayoutAttributeTop
                              multiplier:1
                                constant:0],
    [NSLayoutConstraint constraintWithItem:bannerView
                               attribute:NSLayoutAttributeCenterX
                               relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                               attribute:NSLayoutAttributeCenterX
                              multiplier:1
                                constant:0]
                                ]];
}
  

@end

请注意,在本例中,我们没有给出宽度或高度限制,因为提供的广告尺寸会为横幅广告提供固有内容尺寸,用来调整视图大小。

如果您不想使用以常量定义的标准尺寸,则可以使用 GADAdSizeFromCGSize 设置自定义尺寸。有关详情,请参阅横幅广告尺寸部分

配置 GADBannerView 属性

为了加载和展示广告,需要设置GADBannerView的以下属性:

  • rootViewController - 此视图控制器用于在用户点击广告后呈现重叠式广告。通常应将其设置为包含GADBannerView的视图控制器。
  • adUnitID - 广告单元 ID,GADBannerView应通过此 ID 加载广告。

以下代码示例展示了如何在 UIViewController 的 viewDidLoad 方法中设置这两个必需的属性:

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  ...

  bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
  bannerView.rootViewController = self
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  ...

  self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
  self.bannerView.rootViewController = self;
}

加载广告

GADBannerView创建完毕并配置其属性后,就可以加载广告了,对GADRequest对象调用 loadRequest: 可以实现广告加载:

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  ...

  bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
  bannerView.rootViewController = self
  bannerView.load(GADRequest())
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  ...

  self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
  self.bannerView.rootViewController = self;
  [self.bannerView loadRequest:[GADRequest request]];
}

GADRequest 对象代表单个广告请求,并包含定位信息等内容的属性。

广告事件

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

注册横幅广告事件

要注册横幅广告事件,请将GADBannerView上的 delegate 属性设置为实现 GADBannerViewDelegate 协议的对象。一般情况下,实现横幅广告的类也充当代理类,在这种情况下,可将 delegate 属性设为 self

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

  var bannerView: GADBannerView!

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

Objective-C

@import GoogleMobileAds;

@interface ViewController () <GADBannerViewDelegate>

@property(nonatomic, strong) GADBannerView *bannerView;

@end

@implementation ViewController

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

实现横幅广告事件

GADBannerViewDelegate 中的每个方法都是可选方法,因此您只需实现所需的方法即可。以下示例实现了每个方法,并将消息记录到控制台:

Swift

/// Tells the delegate an ad request loaded an ad.
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
  print("adViewDidReceiveAd")
}

/// Tells the delegate an ad request failed.
func adView(_ bannerView: GADBannerView,
    didFailToReceiveAdWithError error: GADRequestError) {
  print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}

/// Tells the delegate that a full-screen view will be presented in response
/// to the user clicking on an ad.
func adViewWillPresentScreen(_ bannerView: GADBannerView) {
  print("adViewWillPresentScreen")
}

/// Tells the delegate that the full-screen view will be dismissed.
func adViewWillDismissScreen(_ bannerView: GADBannerView) {
  print("adViewWillDismissScreen")
}

/// Tells the delegate that the full-screen view has been dismissed.
func adViewDidDismissScreen(_ bannerView: GADBannerView) {
  print("adViewDidDismissScreen")
}

/// Tells the delegate that a user click will open another app (such as
/// the App Store), backgrounding the current app.
func adViewWillLeaveApplication(_ bannerView: GADBannerView) {
  print("adViewWillLeaveApplication")
}

Objective-C

/// Tells the delegate an ad request loaded an ad.
- (void)adViewDidReceiveAd:(GADBannerView *)adView {
  NSLog(@"adViewDidReceiveAd");
}

/// Tells the delegate an ad request failed.
- (void)adView:(GADBannerView *)adView
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@"adView:didFailToReceiveAdWithError: %@", [error localizedDescription]);
}

/// Tells the delegate that a full-screen view will be presented in response
/// to the user clicking on an ad.
- (void)adViewWillPresentScreen:(GADBannerView *)adView {
  NSLog(@"adViewWillPresentScreen");
}

/// Tells the delegate that the full-screen view will be dismissed.
- (void)adViewWillDismissScreen:(GADBannerView *)adView {
  NSLog(@"adViewWillDismissScreen");
}

/// Tells the delegate that the full-screen view has been dismissed.
- (void)adViewDidDismissScreen:(GADBannerView *)adView {
  NSLog(@"adViewDidDismissScreen");
}

/// Tells the delegate that a user click will open another app (such as
/// the App Store), backgrounding the current app.
- (void)adViewWillLeaveApplication:(GADBannerView *)adView {
  NSLog(@"adViewWillLeaveApplication");
}

有关 iOS API Demo 应用中横幅广告代理方法的实现方式,请参阅广告代理示例。

Swift Objective-C

实际应用示例

以下是这些广告事件方法的一些实际应用示例。

在接收到广告之后才将横幅广告添加到视图层次结构中

在接收到广告前,您可能暂不希望将GADBannerView添加到视图层次结构中。为此,您可以监听 adViewDidReceiveAd: 事件:

Swift

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

Objective-C

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

以动画方式展示横幅广告

在返回横幅广告后,您也可以利用 adViewDidReceiveAd: 事件以动画方式展示该广告,如下例所示:

Swift

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

Objective-C

- (void)adViewDidReceiveAd:(GADBannerView *)adView {
  adView.alpha = 0;
  [UIView animateWithDuration:1.0 animations:^{
    adView.alpha = 1;
  }];
}

暂停和恢复应用

GADBannerViewDelegate 协议包含用于发送下列事件通知的方法,包括:点击导致呈现或关闭叠加层、调用了外部浏览器等。如果您希望跟踪这些事件是否由于广告而发生的,请注册这些 GADBannerViewDelegate 方法。

如果您要获取所有类型(而不仅仅是由于广告点击而发生)的重叠式广告展示或外部浏览器调用,您的应用最好监听 UIViewControllerUIApplication 上具有同样功能的方法。下表显示了可与 GADBannerViewDelegate 方法同时调用且具有同样功能的 iOS 方法:

GADBannerViewDelegate 方法 iOS 方法
adViewWillPresentScreen: UIViewController 的 viewWillDisappear:
adViewWillDismissScreen: UIViewController 的 viewWillAppear:
adViewDidDismissScreen: UIViewController 的 viewDidAppear:
adViewWillLeaveApplication: UIApplicationDelegate 的 applicationDidEnterBackground:

下表列出了标准横幅广告尺寸。

尺寸(宽 x 高,以点为单位) 说明 适用范围 AdSize 常量
320x50 横幅广告 手机和平板电脑 kGADAdSizeBanner
320x100 大型横幅广告 手机和平板电脑 kGADAdSizeLargeBanner
300x250 IAB 中矩形 手机和平板电脑 kGADAdSizeMediumRectangle
468x60 IAB 全尺寸横幅广告 平板电脑 kGADAdSizeFullBanner
728x90 IAB 页首横幅广告 平板电脑 kGADAdSizeLeaderboard
屏幕宽度 x 32|50|90 智能横幅广告 手机和平板电脑 kGADAdSizeSmartBannerPortrait
kGADAdSizeSmartBannerLandscape

自定义广告尺寸

要定义自定义横幅广告尺寸,请使用 GADAdSizeFromCGSize 设置所需的尺寸,如下所示:

Swift

let adSize = GADAdSizeFromCGSize(CGSize(width: 300, height: 50))

Objective-C

GADAdSize size = GADAdSizeFromCGSize(CGSizeMake(300, 50));

智能横幅广告

智能横幅广告是一种广告单元,可在任意尺寸的各种设备上展示与屏幕等宽的横幅广告,无论设备屏幕是横向还是纵向都没问题。智能横幅广告可以检测设备处于当前屏幕方向时的宽度,并据此创建与之等宽的广告视图。

在 iPhone 上,当屏幕为纵向时,智能横幅广告高度为 50 点;当屏幕为横向时,广告高度为 32 点。在 iPad 上,智能横幅广告高度在屏幕为纵向和横向时均为 90 点。

当图片广告不足以占据所分配的整个空间时,系统会居中放置图片,然后填充两侧剩余的空间。

要使用智能横幅广告,只需为广告尺寸指定 kGADAdSizeSmartBannerPortrait(适用于纵向屏幕)或 kGADAdSizeSmartBannerLandscape(适用于横向屏幕)即可:

Swift

let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)

Objective-C

GADBannerView *bannerView = [[GADBannerView alloc]
      initWithAdSize:kGADAdSizeSmartBannerPortrait];

由于 iOS 11 增加了安全区域,因此对于全宽横幅广告,您还应添加对其边缘的限制,使之不超过安全区域的边缘。以下代码段展示了如何执行此操作:

Swift

func addBannerViewToView(_ bannerView: GADBannerView) {
  bannerView.translatesAutoresizingMaskIntoConstraints = false
  view.addSubview(bannerView)
  if #available(iOS 11.0, *) {
    // In iOS 11, we need to constrain the view to the safe area.
    positionBannerViewFullWidthAtBottomOfSafeArea(bannerView)
  }
  else {
    // In lower iOS versions, safe area is not available so we use
    // bottom layout guide and view edges.
    positionBannerViewFullWidthAtBottomOfView(bannerView)
  }
}

// MARK: - view positioning
@available (iOS 11, *)
func positionBannerViewFullWidthAtBottomOfSafeArea(_ bannerView: UIView) {
  // Position the banner. Stick it to the bottom of the Safe Area.
  // Make it constrained to the edges of the safe area.
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
    guide.leftAnchor.constraint(equalTo: bannerView.leftAnchor),
    guide.rightAnchor.constraint(equalTo: bannerView.rightAnchor),
    guide.bottomAnchor.constraint(equalTo: bannerView.bottomAnchor)
  ])
}

func positionBannerViewFullWidthAtBottomOfView(_ bannerView: UIView) {
  view.addConstraint(NSLayoutConstraint(item: bannerView,
                                        attribute: .leading,
                                        relatedBy: .equal,
                                        toItem: view,
                                        attribute: .leading,
                                        multiplier: 1,
                                        constant: 0))
  view.addConstraint(NSLayoutConstraint(item: bannerView,
                                        attribute: .trailing,
                                        relatedBy: .equal,
                                        toItem: view,
                                        attribute: .trailing,
                                        multiplier: 1,
                                        constant: 0))
  view.addConstraint(NSLayoutConstraint(item: bannerView,
                                        attribute: .bottom,
                                        relatedBy: .equal,
                                        toItem: bottomLayoutGuide,
                                        attribute: .top,
                                        multiplier: 1,
                                        constant: 0))
}

Objective-C

- (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  if (@available(ios 11.0, *)) {
    // In iOS 11, we need to constrain the view to the safe area.
    [self positionBannerViewFullWidthAtBottomOfSafeArea:bannerView];
  } else {
    // In lower iOS versions, safe area is not available so we use
    // bottom layout guide and view edges.
    [self positionBannerViewFullWidthAtBottomOfView:bannerView];
  }
}

#pragma mark - view positioning

- (void)positionBannerViewFullWidthAtBottomOfSafeArea:(UIView *_Nonnull)bannerView NS_AVAILABLE_IOS(11.0) {
  // Position the banner. Stick it to the bottom of the Safe Area.
  // Make it constrained to the edges of the safe area.
  UILayoutGuide *guide = self.view.safeAreaLayoutGuide;

  [NSLayoutConstraint activateConstraints:@[
    [guide.leftAnchor constraintEqualToAnchor:bannerView.leftAnchor],
    [guide.rightAnchor constraintEqualToAnchor:bannerView.rightAnchor],
    [guide.bottomAnchor constraintEqualToAnchor:bannerView.bottomAnchor]
  ]];
}

- (void)positionBannerViewFullWidthAtBottomOfView:(UIView *_Nonnull)bannerView {
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeLeading
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeLeading
                                                       multiplier:1
                                                         constant:0]];
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeTrailing
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeTrailing
                                                       multiplier:1
                                                         constant:0]];
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeBottom
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.bottomLayoutGuide
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1
                                                         constant:0]];
}

其他资源

GitHub 上的示例

“Mobile Ads Garage”视频教程

后续步骤

发送以下问题的反馈:

此网页
需要帮助?请访问我们的支持页面