バナー広告

バナー広告は、デバイス画面の上部か下部にアプリのレイアウト内の一部分を使用して表示されます。アプリの操作中は画面に表示され続けますが、一定時間が経過すると自動的に更新されるよう設定できます。モバイル広告を初めてお使いの場合は、この広告から始めることをおすすめします。

このガイドでは、Ad Manager のバナー広告を iOS アプリに組み込む方法について説明します。コード スニペットと設定手順のほか、バナーの適切なサイズに関する情報、他の関連情報へのリンクも紹介します。

前提条件

テストは必ずテスト広告で行う

アプリの作成とテストでは必ずテスト広告を使用し、配信中の実際の広告は使用しないでください。実際の広告を使用すると、アカウントが停止される可能性があります。

テスト広告は、次に示す iOS バナー広告向けのテスト専用広告ユニット ID を使うと簡単に読み込むことができます。 /6499/example/banner

この ID は、すべてのリクエストに対してテスト広告を返すように構成されており、アプリのコーディング、テスト、デバッグで自由に使うことができます。なお、テスト用 ID は、アプリを公開する前に必ずご自身の広告ユニット ID に置き換えてください。

Mobile Ads SDK のテスト広告の仕組みについて詳しくは、テスト広告をご覧ください。

GAMBannerViewを作成する

バナー広告は GAMBannerView オブジェクトに表示されるため、バナー広告を組み込む最初のステップは、ビュー階層に GAMBannerView を含めることです。この手順は、通常 Interface Builder かプログラムで行います。

インターフェース ビルダー

GAMBannerView は、通常のビューと同様にストーリーボードまたは xib ファイルに追加できます。このメソッドを使用する場合は、表示する広告サイズに合わせて幅と高さの制約を追加してください。たとえば、バナー(320×50)を表示する場合は、320 ポイントの幅制約と 50 ポイントの高さ制約を使用します。

プログラム

GAMBannerView は、直接インスタンス化することもできます。次の例では、GAMBannerView を作成し、画面のセーフエリアの下中央に合わせて配置して、バナーのサイズを 320×50 に設定しています。

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  var bannerView: GAMBannerView!

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

    addBannerViewToView(bannerView)
  }

  func addBannerViewToView(_ bannerView: GAMBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    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)
      ])
   }
   
}

Objective-C

@import GoogleMobileAds;

@interface ViewController ()

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

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

  [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.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

この場合、提供される広告サイズによってバナーのコンテンツ サイズが決まるため、幅や高さの制約は与えません。

定数で定義された標準サイズを使用しない場合は、GADAdSizeFromCGSize を使用してカスタムサイズを設定できます。詳しくは、バナーサイズのセクションをご覧ください。

プロパティを GAMBannerView 構成

広告を読み込んで表示するには、GAMBannerView にいくつかのプロパティを設定する必要があります。

  • rootViewController - このビュー コントローラは、広告のクリック時にオーバーレイを表示するために使用されます。通常は、GAMBannerView を含むビュー コントローラに設定されます。
  • adUnitID - GAMBannerView が広告を読み込む先の広告ユニットの ID です。

次のコードサンプルは、UIViewController の viewDidLoad メソッドで 2 つの必須プロパティを設定する方法を示したものです。

Swift

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

  bannerView.adUnitID = "/6499/example/banner"
  bannerView.rootViewController = self
}

Objective-C

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

  self.bannerView.adUnitID = @"/6499/example/banner";
  self.bannerView.rootViewController = self;
}

広告を読み込む

GAMBannerView を配置してそのプロパティを設定したら、いよいよ広告を読み込みます。これを行うには、GAMRequest オブジェクトの loadRequest: を呼び出します。

Swift

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

  bannerView.adUnitID = "/6499/example/banner"
  bannerView.rootViewController = self
  bannerView.load(GAMRequest())
}

Objective-C

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

  self.bannerView.adUnitID = @"/6499/example/banner";
  self.bannerView.rootViewController = self;
  [self.bannerView loadRequest:[GAMRequest request]];
}

GAMRequest オブジェクトは単一の広告リクエストを表し、ターゲティング情報などのプロパティを含みます。

広告ユニットの更新を設定していれば、広告の読み込みに失敗した場合でも、別の広告を明示的にリクエストする必要はありません。Google Mobile Ads SDK では、Ad Manager 管理画面で指定された更新頻度が適用されます。更新を有効にしていない場合は、新しいリクエストを発行する必要があります。

広告イベント

GADBannerViewDelegate を使用すると、広告が閉じられた、ユーザーがアプリを離れたなどのライフサイクル イベントをリッスンできます。

バナー イベントを登録する

バナー広告イベントを登録するには、GADBannerViewDelegate プロトコルを実装しているオブジェクトに、GAMBannerViewdelegate プロパティを設定します。通常は、バナー広告を実装するクラスがデリゲート クラスとしての役割も果たすため、その場合は delegate プロパティを self に設定できます。

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    ...
    bannerView.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 as above.
  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 メソッドを登録します。

あらゆるタイプのオーバーレイ表示や外部ブラウザの起動を確認するには、広告クリックで呼び出されるメソッドだけでなく、UIViewController または UIApplication の同等のメソッドをアプリでリッスンすることをおすすめします。以下の表には、GADBannerViewDelegate のメソッドと同じタイミングで呼び出される、iOS の同等のメソッドが示されています。

GADBannerViewDelegate のメソッド iOS のメソッド
bannerViewWillPresentScreen: UIViewController の viewWillDisappear:
bannerViewWillDismissScreen: UIViewController の viewWillAppear:
bannerViewDidDismissScreen: UIViewController の viewDidAppear:

標準のバナーサイズについては、以下の表をご覧ください。

ポイント単位(幅×高さ) 説明 対象 AdSize の定数値
320x50 バナー スマートフォンとタブレット GADAdSizeBanner
320×100 バナー(大) スマートフォンとタブレット GADAdSizeLargeBanner
300×250 IAB レクタングル(中) スマートフォンとタブレット GADAdSizeMediumRectangle
468×60 IAB フルサイズ バナー タブレット GADAdSizeFullBanner
728×90 IAB ビッグバナー タブレット GADAdSizeLeaderboard
指定された幅 × 最適な高さ アダプティブ バナー 携帯電話とタブレット なし

カスタム広告サイズ

カスタムのバナーサイズを定義するには、GADAdSizeFromCGSize を使って希望のサイズを次のように設定します。

Swift

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

Objective-C

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

カスタム広告サイズ

Google アド マネージャーでは、標準の広告ユニットに加えて、任意のサイズの広告ユニットをアプリに配信できます。広告リクエストで定義する広告サイズ(幅、高さ)は、アプリに表示される広告ビューのサイズ(GAMBannerView)と一致させる必要があります。カスタムサイズを設定するには、GADAdSizeFromCGSize を使用します。

Swift

// Define custom GADAdSize of 250x250 for GAMBannerView.
let customAdSize = GADAdSizeFromCGSize(CGSize(width: 250, height: 250))
bannerView = GAMBannerView(adSize: customAdSize)

Objective-C

// Define custom GADAdSize of 250x250 for GAMBannerView
GADAdSize customAdSize = GADAdSizeFromCGSize(CGSizeMake(250, 250));
self.bannerView = [[GAMBannerView alloc] initWithAdSize:customAdSize];

iOS API デモアプリでカスタム広告サイズを実装するには、アド マネージャーによる複数の広告サイズの実装例をご覧ください。

Swift Objective-C

複数の広告サイズ

アド マネージャーでは、GAMBannerView の配信対象となる広告サイズを複数指定できます。この機能を使用するためのステップは、次の 3 つです。

  1. アド マネージャーの管理画面で、広告ユニットを対象とする広告申込情報を作成し、サイズが異なる複数のクリエイティブに関連付けます。

  2. アプリで、validAdSizes プロパティを GAMBannerView に設定します。

    Swift

    // Define an optional array of GADAdSize to specify all valid sizes that are appropriate
    // for this slot. Never create your own GADAdSize directly. Use one of the
    // predefined standard ad sizes (such as GADAdSizeBanner), or create one using
    // the GADAdSizeFromCGSize method.
    //
    // Note: Ensure that the allocated GAMBannerView is defined with an ad size. Also note
    // that all desired sizes should be included in the validAdSizes array.
    bannerView.validAdSizes = [NSValueFromGADAdSize(GADAdSizeBanner),
        NSValueFromGADAdSize(GADAdSizeMediumRectangle),
        NSValueFromGADAdSize(GADAdSizeFromCGSize(CGSize(width: 120, height: 20)))]
    

    Objective-C

    // Define an optional array of GADAdSize to specify all valid sizes that are appropriate
    // for this slot. Never create your own GADAdSize directly. Use one of the
    // predefined standard ad sizes (such as GADAdSizeBanner), or create one using
    // the GADAdSizeFromCGSize method.
    //
    // Note: Ensure that the allocated GAMBannerView is defined with an ad size. Also note
    // that all desired sizes should be included in the validAdSizes array.
    self.bannerView.validAdSizes = @[
        NSValueFromGADAdSize(GADAdSizeBanner),
        NSValueFromGADAdSize(GADAdSizeMediumRectangle),
        NSValueFromGADAdSize(GADAdSizeFromCGSize(CGSizeMake(120, 20)))
    ];
    
  3. 広告サイズの変化を検出するために、GADAdSizeDelegate メソッドを実装します。

    Swift

    public func bannerView(_ bannerView: GADBannerView, willChangeAdSizeTo size: GADAdSize)
    

    Objective-C

    • (void)bannerView:(GAMBannerView *)view willChangeAdSizeTo:(GADAdSize)size;
  4. 広告のリクエストの前にデリゲートを設定します。

    Swift

    bannerView.adSizeDelegate = self

    Objective-C

    self.bannerView.adSizeDelegate = self;

iOS API デモアプリでカスタム広告サイズを実装するには、アド マネージャーによる複数の広告サイズの実装例をご覧ください。

Swift Objective-C

インプレッションの手動カウント

インプレッションを記録するタイミングについて特別な条件がある場合は、インプレッションの ping をアド マネージャーに手動で送信できます。それには、広告を読み込む前に、GAMBannerView で手動インプレッションを有効にします。

Swift

bannerView.enableManualImpressions = true

Objective-C

self.bannerView.enableManualImpressions = YES;

広告が正常に返され、画面に表示されていることを確認したら、インプレッションを手動でカウントします。

Swift

bannerView.recordImpression()

Objective-C

[self.bannerView recordImpression];

アプリ内イベント

アプリ内イベントを利用することで、アプリのコードにメッセージを送信する広告を作成できます。アプリは、送信されたメッセージに基づいてアクションを実行できます。

アド マネージャー専用のアプリ内イベントをリッスンするには、GADAppEventDelegate を使用します。これらのイベントは、広告ライフサイクルのあらゆるタイミングで(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 デモアプリでアプリ内イベントを実装するには、アド マネージャーによるアプリ内イベントの実装例をご覧ください。

Swift Objective-C

補足資料

GitHub の例

Mobile Ads Garage の動画チュートリアル

次のステップ

詳しくは、ユーザーのプライバシーについての記事をご覧ください。