バナー広告は、アプリのレイアウトの一部に表示される長方形の広告です。ユーザーがアプリを操作している間、画面の上部または下部に固定されるか、ページをスクロールした時にコンテンツと一緒に移動します。一定時間が経過すると自動的に更新されるよう設定することができます。詳しくは、バナー広告の概要をご覧ください。
このガイドでは、指定した広告の幅を使用してデバイスごとに広告のサイズを最適化することで、パフォーマンスを最大限に高めるアンカー アダプティブ バナー広告の利用を開始する方法について説明します。
アンカー アダプティブ バナー
アンカー アダプティブ バナー広告は、通常の固定サイズの広告ではなく、アスペクト比が固定された広告です。アスペクト比は、業界標準の 320×50 とほぼ同じです。利用できるスペースの全幅を指定すると、その幅に最適な高さの広告が返されます。同じデバイスからのリクエストでは最適な高さは変わらないため、広告が更新されても周囲のビューを動かす必要はありません。
前提条件
- スタートガイドの手順を完了していること
常にテスト広告でテストする
アプリの開発とテストでは必ずテスト広告を使用し、配信中の実際の広告は使用しないでください。実際の広告でテストすると、アカウントが停止される場合があります。
次の iOS バナー向けのテスト専用広告ユニット ID を使うと、テスト広告を簡単に読み込むことができます。
/21775744923/example/adaptive-banner
この ID は、すべてのリクエストに対してテスト広告を返すように設定されており、アプリのコーディング、テスト、デバッグで自由に使用することができます。なお、テスト用 ID は、アプリを公開する前に必ずご自身の広告ユニット ID に置き換えてください。
Mobile Ads SDK のテスト広告の仕組みについて詳しくは、テスト広告をご覧ください。
GAMBannerView を作成する
バナー広告は GAMBannerView オブジェクトに表示されるため、バナー広告を組み込む最初のステップは、ビュー階層に GAMBannerView を含めることです。通常、この手順はプログラムまたは Interface Builder で行います。
プログラムで行う場合
GAMBannerView は、直接インスタンス化することもできます。GAMBannerView の作成例を次に示します。
Swift
// Initialize the BannerView.
bannerView = BannerView()
bannerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bannerView)
// This example doesn't give width or height constraints, as the ad size gives the banner an
// intrinsic content size to size the view.
NSLayoutConstraint.activate([
  // Align the banner's bottom edge with the safe area's bottom edge
  bannerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
  // Center the banner horizontally in the view
  bannerView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
])
SwiftUI
AdManagerBannerView を使用するには、UIViewRepresentable を作成します。
private struct BannerViewContainer: UIViewRepresentable {
  typealias UIViewType = BannerView
  let adSize: AdSize
  init(_ adSize: AdSize) {
    self.adSize = adSize
  }
  func makeUIView(context: Context) -> BannerView {
    let banner = BannerView(adSize: adSize)
    banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
    banner.load(Request())
    banner.delegate = context.coordinator
    return banner
  }
  func updateUIView(_ uiView: BannerView, context: Context) {}
  func makeCoordinator() -> BannerCoordinator {
    return BannerCoordinator(self)
  }
height 値と width 値を指定して、ビュー階層に UIViewRepresentable を追加します。
var body: some View {
  Spacer()
  // Request an anchored adaptive banner with a width of 375.
  let adSize = currentOrientationAnchoredAdaptiveBanner(width: 375)
  BannerViewContainer(adSize)
    .frame(width: adSize.size.width, height: adSize.size.height)
}
Objective-C
// Initialize the GADBannerView.
self.bannerView = [[GADBannerView alloc] init];
self.bannerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.bannerView];
// This example doesn't give width or height constraints, as the ad size gives the banner an
// intrinsic content size to size the view.
[NSLayoutConstraint activateConstraints:@[
    // Align the banner's bottom edge with the safe area's bottom edge
    [self.bannerView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
    // Center the banner horizontally in the view
    [self.bannerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
]];
Interface Builder で行う場合
GAMBannerView は、ストーリーボードまたは xib ファイルに追加できます。このメソッドを使用する場合は、バナーに掲載位置の制約のみを追加してください。たとえば、アダプティブ バナーを画面下部に表示する場合は、バナービューの下端を下部レイアウト ガイドの上端に設定し、centerX の制約を superview の centerX に設定します。
広告のサイズを設定する
GADSize を、幅が指定されたアンカー アダプティブ バナータイプに設定します。
Swift
// Request an anchored adaptive banner with a width of 375.
bannerView.adSize = currentOrientationAnchoredAdaptiveBanner(width: 375)
Objective-C
// Request an anchored adaptive banner with a width of 375.
self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(375);
広告を読み込む
GAMBannerView を配置して、adUnitID などのプロパティを設定したら、いよいよ広告を読み込みます。それには GAMRequest オブジェクトの loadRequest: を呼び出します。
Swift
bannerView.load(AdManagerRequest())
SwiftUI
banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
banner.load(Request())
Objective-C
[self.bannerView loadRequest:[GAMRequest request]];
GAMRequest オブジェクトは単一の広告リクエストを表し、ターゲティング情報などのプロパティを含みます。
広告を更新する
広告ユニットの更新を有効にしていれば、広告の読み込みに失敗しても、別の広告をリクエストする必要はありません。Google Mobile Ads SDK では、アド マネージャーの管理画面で指定した更新頻度が使用されます。更新を有効にしていない場合は、新しいリクエストを発行します。更新頻度の設定など、広告ユニットの更新について詳しくは、モバイルアプリでの広告の更新頻度をご覧ください。
向きの変更を処理する
アプリの画面の向きが(portrait モードから横向きなどに)変わると、バナーに利用できるスペースの横幅も変わることがよくあります。新しいレイアウトに適切なサイズの広告を表示するには、新しいバナーをリクエストします。バナーの幅が固定されている場合、またはレイアウトの制約でサイズ変更を処理できる場合は、この手順をスキップしてください。
Swift
override func viewWillTransition(
  to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator
) {
  coordinator.animate(alongsideTransition: { _ in
    // Load a new ad for the new orientation.
  })
}
Objective-C
- (void)viewWillTransitionToSize:(CGSize)size
       withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
    // Load a new ad for the new orientation.
  } completion:nil];
}
広告イベント
広告が閉じられたときや、ユーザーがアプリから離れたときなどのライフサイクル イベントは、GADBannerViewDelegate を使用してリッスンできます。
バナーイベントを登録する
バナー広告イベントを登録するには、GADBannerViewDelegate プロトコルを実装しているオブジェクトに、GAMBannerView の delegate プロパティを設定します。通常は、バナー広告を実装するクラスがデリゲート クラスとしての役割も果たすため、その場合は delegate プロパティに self を設定できます。
Swift
bannerView.delegate = self
SwiftUI
banner.delegate = context.coordinator
Objective-C
self.bannerView.delegate = self;
バナーイベントを実装する
GADBannerViewDelegate の各メソッドはオプションのため、必要なメソッドを実装すれば問題ありません。各メソッドを実装してメッセージのログをコンソールに記録する場合のサンプルを、次に示します。
Swift
func bannerViewDidReceiveAd(_ bannerView: BannerView) {
  print(#function)
}
func bannerView(_ bannerView: BannerView, didFailToReceiveAdWithError error: Error) {
  print(#function + ": " + error.localizedDescription)
}
func bannerViewDidRecordClick(_ bannerView: BannerView) {
  print(#function)
}
func bannerViewDidRecordImpression(_ bannerView: BannerView) {
  print(#function)
}
func bannerViewWillPresentScreen(_ bannerView: BannerView) {
  print(#function)
}
func bannerViewWillDismissScreen(_ bannerView: BannerView) {
  print(#function)
}
func bannerViewDidDismissScreen(_ bannerView: BannerView) {
  print(#function)
}
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 デモアプリでバナー デリゲート メソッドを使用するには、広告デリゲートのサンプルをご覧ください。
ユースケース
これらの広告イベント メソッドの使用に適したケースをいくつか紹介します。
広告を取得してからバナーをビュー階層に追加する
広告が取得されるまで、ビュー階層に GAMBannerView を追加するのを遅らせたい場合は、次のように bannerViewDidReceiveAd: イベントをリッスンします。
Swift
func bannerViewDidReceiveAd(_ bannerView: BannerView) {
  // 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: BannerView) {
  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: | 
インプレッションの手動カウント
インプレッションを記録するタイミングについて特別な条件がある場合は、インプレッションの信号をアド マネージャーに手動で送信できます。それには、広告を読み込む前に、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: AdManagerBannerView,
    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, AppEventDelegate {}
Objective-C
@import GoogleMobileAds;
@interface ViewController : UIViewController <GADAppEventDelegate> {}
@end
広告のリクエストを行う前に、appEventDelegate プロパティを使用してデリゲートを設定します。
Swift
bannerView.appEventDelegate = self
Objective-C
self.bannerView.appEventDelegate = self;
アプリ内イベントに応じてアプリの背景色が指定した色に変わるようにする方法は次のとおりです。
Swift
func bannerView(_ banner: AdManagerBannerView, 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 デモアプリでアプリ内イベントを実装するには、アド マネージャーによるアプリ内イベントの実装例をご覧ください。
参考情報
GitHub の例
- アンカー アダプティブ バナー広告の例: Swift | SwiftUI | Objective-C
- 高度な機能のデモ: Swift | Objective-C
次のステップ
折りたたみ可能バナー
折りたたみ可能バナー広告は、最初は大きなオーバーレイとして表示されるバナー広告で、広告を小さいサイズに折りたたむボタンが付いています。パフォーマンスをさらに最適化するために、この機能の使用を検討してください。詳しくは、折りたたみ可能バナー広告をご覧ください。
インライン アダプティブ バナー
インライン アダプティブ バナーは、アンカー アダプティブ バナーよりも大きく、高さのあるバナーです。インライン アダプティブ バナーでは高さが変動するため、デバイス画面と同じ大きさで表示できます。 スクロール可能なコンテンツにバナー広告を配置するアプリでは、アンカー アダプティブ バナー広告よりもインライン アダプティブ バナーの使用をおすすめします。詳しくは、インライン アダプティブ バナーをご覧ください。