バナー広告

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

このガイドでは、バナー広告をAd Manager から iOS アプリに統合する方法を説明します。コード スニペットと設定手順に加え、バナーの適切なサイズ情報や、参考情報へのリンクも記載されています。

Prerequisites

常にテスト広告でテストする

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

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

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

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

GAMBannerViewの作成

バナー広告は GAMBannerView オブジェクトで表示されるため、バナー広告を統合するための最初のステップは、ビュー階層に GAMBannerView を含めることです。この処理は、通常 Interface Builder またはプログラムを使用して行います。

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

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

プログラム

GAMBannerView は直接インスタンス化することもできます。次の例では、GAMBannerView を作成し、画面のセーフエリアの下中央に揃え、バナーサイズを 320x50 にしています。

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 オブジェクトは 1 つの広告リクエストを表し、ターゲティング情報などのプロパティが格納されます。

広告イベント

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

バナーイベントの登録

バナー広告イベントを登録するには、GAMBannerViewdelegate プロパティを、GADBannerViewDelegate プロトコルを実装するオブジェクトに設定します。一般に、バナー広告を実装するクラスは、デリゲート クラスとしても機能します。その場合、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 デモアプリでバナー デリゲート メソッドを実装するには、Ad Delegate の例をご覧ください。

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:39
bannerViewWillDismissScreen: UIViewController&viewWillAppear:39
bannerViewDidDismissScreen: UIViewController&viewDidAppear:39

下の表に標準バナーのサイズを示します。

ポイントのサイズ(WxH) 説明 可用性 AdSize 定数
320×50 バナー スマートフォンとタブレット GADAdSizeBanner
320×100 バナー(大) スマートフォンとタブレット GADAdSizeLargeBanner
300×250 IAB のレクタングル(中) スマートフォンとタブレット GADAdSizeMediumRectangle
468×60 IAB フルサイズ バナー タブレット GADAdSizeFullBanner
728×90 IAB リーダーボード タブレット GADAdSizeLeaderboard
指定の幅 x アダプティブの高さ アダプティブ バナー 携帯電話とタブレット N/A

カスタム広告サイズ

カスタム バナーサイズを定義するには、次のように 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. アプリで GAMBannerViewvalidAdSizes プロパティを設定します。

    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 の動画チュートリアル

次のステップ

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