バナー広告

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

このガイドでは、アンカー広告 アダプティブ バナー広告 「新規顧客の獲得」目標を使ってデバイスごとに 広告サイズを最適化することで 広告の幅を指定します。

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

アンカー アダプティブ バナー広告は、通常の固定サイズ広告ではなく、固定アスペクト比の広告です。アスペクト比は業界標準である 320x50 と同様です。使用可能な最大幅を指定すると、その幅に最適な高さの広告が返されます。最適な高さは、同じ場所からのリクエスト間で変化しない 広告の更新時に周囲のビューを移動する必要がないようにします。

前提条件

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

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

テスト広告を読み込むには、iOS 向けのテスト専用広告ユニット ID を使う方法が最も簡単です バナー:

/21775744923/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)
    // This example doesn't give width or height constraints, as the provided
    // ad size gives the banner an intrinsic content size to size the view.
    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)
      ])
  }
}

SwiftUI

GAMBannerView を使用するには、UIViewRepresentable を作成します。

private struct BannerView: UIViewRepresentable {
  let adSize: GADAdSize

  init(_ adSize: GADAdSize) {
    self.adSize = adSize
  }

  func makeUIView(context: Context) -> UIView {
    // Wrap the GADBannerView in a UIView. GADBannerView automatically reloads a new ad when its
    // frame size changes; wrapping in a UIView container insulates the GADBannerView from size
    // changes that impact the view returned from makeUIView.
    let view = UIView()
    view.addSubview(context.coordinator.bannerView)
    return view
  }

  func updateUIView(_ uiView: UIView, context: Context) {
    context.coordinator.bannerView.adSize = adSize
  }

  func makeCoordinator() -> BannerCoordinator {
    return BannerCoordinator(self)
  }

GAMBannerView の初期化と動作を管理するには、 Coordinator:

class BannerCoordinator: NSObject, GADBannerViewDelegate {

  private(set) lazy var bannerView: GADBannerView = {
    let banner = GADBannerView(adSize: parent.adSize)
    banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
    banner.load(GADRequest())
    banner.delegate = self
    return banner
  }()

  let parent: BannerView

  init(_ parent: BannerView) {
    self.parent = parent
  }

ビューの幅を取得するには、GeometryReader を使用します。このクラス 現在のデバイスの向きに適した広告サイズを計算します。「 frame は、広告サイズから計算された高さに設定されます。

var body: some View {
  GeometryReader { geometry in
    let adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(geometry.size.width)

    VStack {
      Spacer()
      BannerView(adSize)
        .frame(height: adSize.size.height)
    }
  }

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];
  // This example doesn't give width or height constraints, as the provided
  // ad size gives the banner an intrinsic content size to size the view.
  [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 ファイルに追加できます。使用する場合 メソッドを使う場合は、位置の制約はバナーにのみ追加してください。たとえば 画面の下部にアダプティブ バナーを表示する場合は、 のバナービューのトップ 1 とボトム レイアウト ガイドの上部と同じ位置を指定し、 centerX スーパービューの centerX と等しい制約が適用されます。

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

Swift

bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

Objective-C

self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);

広告を読み込む

GAMBannerView とそのプロパティが設定されると、 広告を読み込みます。これを行うには、loadRequest:GAMRequest オブジェクト:

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  // Set the ad unit ID and view controller that contains the GAMBannerView.
  bannerView.adUnitID = "/21775744923/example/adaptive-banner"
  bannerView.rootViewController = self

  bannerView.load(GAMRequest())
}

SwiftUI

banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
banner.load(GADRequest())

Objective-C

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

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

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

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

広告イベント

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

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

バナー広告イベントを登録するには、delegate プロパティを GAMBannerView を、 GADBannerViewDelegate プロトコル。一般にバナー広告を実装するクラスは 広告もデリゲート クラスとして機能します。この場合、delegate プロパティはデリゲート クラスとして機能します。 self に設定します。

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

  var bannerView: GAMBannerView!

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

SwiftUI

banner.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.
  addBannerViewToView(bannerView)
}

Objective-C

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

バナー広告をアニメーション表示する

また、bannerViewDidReceiveAd: イベントを使用してバナー広告を 1 回アニメーション化することもできます。 次のように返されます。

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 の同等のメソッド。こちらの表 同時に呼び出される同等の iOS メソッドを示しています。 GADBannerViewDelegate メソッド:

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 の例

次のステップ

折りたたみ可能バナー

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

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

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

他のトピックを見る