バナー広告

バナー広告は、アプリのレイアウトの一部を占める長方形の広告です。広告は、ユーザーがアプリを操作している間、画面上に表示され続けます。画面の上部または下部に固定されるか、ユーザーがスクロールするとコンテンツと一緒に移動します。バナー広告は、一定期間後に自動的に更新されます。詳しくは、バナー広告の概要をご覧ください。

このガイドでは、アンカー アダプティブ バナー広告の使用方法について説明します。この広告を使用すると、指定した幅でデバイスごとに広告サイズを最適化して、パフォーマンスを最大化できます。

アンカー アダプティブ バナー

アンカー アダプティブ バナー広告は、通常の固定サイズの広告ではなく、固定のアスペクト比の広告です。アスペクト比は業界標準の 320×50 と同様です。使用可能な全幅を指定すると、その幅に最適な高さの広告が返されます。最適な高さは、同じデバイスからのリクエストによって変わることはなく、広告の更新時に周囲のビューを移動する必要はありません。

前提条件

必ずテスト広告でテストする

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

テスト広告を読み込む最も簡単な方法は、iOS バナー向けのテスト専用広告ユニット ID を使用することです。 /6499/example/adaptive-banner

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

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

GAMBannerView を作成する

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

プログラム

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)
    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];
  
  // 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];
  [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 ファイルに追加できます。この方法を使用する場合は、位置の制約はバナーにのみ追加してください。たとえば、画面の下部にアダプティブ バナーを表示する場合は、バナービューの下部をボトム レイアウト ガイドの上部と同じに設定し、中央の X をスーパービューの中心 X と等しく設定します。

バナー広告の広告サイズは引き続きプログラムで設定します。

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 = "/6499/example/adaptive-banner"
  bannerView.rootViewController = self

  bannerView.load(GAMRequest())
}

Objective-C

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

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

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

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

広告イベント

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 Demo アプリでのバナー デリゲート メソッドの実装については、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:
bannerViewWillDismissScreen: UIViewController の viewWillAppear:
bannerViewDidDismissScreen: UIViewController の viewDidAppear:

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

インプレッションを記録するタイミングについて特別な条件がある場合は、インプレッション 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 の例

次のステップ

折りたたみ可能バナー

折りたたみ可能バナー広告は、最初は大きなオーバーレイとして表示されるバナー広告で、広告を小さなサイズに折りたたむボタンがあります。これを使用してパフォーマンスをさらに最適化することを検討してください。詳しくは、折りたたみ可能バナー広告をご覧ください。

インライン アダプティブ バナー

インライン アダプティブ バナーは、アンカー アダプティブ バナーよりも大きく縦長です。高さは可変で、デバイス画面と同じ高さにできます。スクロール可能なコンテンツにバナー広告を配置するアプリでは、アンカー アダプティブ バナー広告よりもインライン アダプティブ バナーを使用することをおすすめします。詳しくは、インライン アダプティブ バナーをご覧ください。

他のトピックを見る