Banner Ads

Banner ads are rectangular ads that occupy a portion of an app's layout. They stay on screen while users are interacting with the app, either anchored at the top or bottom of the screen or inline with content as the user scrolls. Banner ads can refresh automatically after a certain period of time. See Overview of banner ads for more information.

This guide shows you how to get started with anchored adaptive banner ads, which maximizes performance by optimizing the ad size for each device using an ad width you specify.

Anchored adaptive banner

Anchored adaptive banner ads are fixed aspect ratio ads rather than the regular fixed size ads. The aspect ratio is similar to 320x50 industry standard. Once you specify the full width available, it returns an ad with optimal height for that width. The optimal height doesn't change across requests from the same device, and the surrounding views don't need to move when the ad refreshes.

Prerequisites

Always test with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for iOS banners:

/21775744923/example/adaptive-banner

It's been specially configured to return test ads for every request, and you're free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK's test ads work, see Test Ads.

Create a GAMBannerView

Banner ads are displayed in GAMBannerView objects, so the first step toward integrating banner ads is to include a GAMBannerView in your view hierarchy. This is typically done either programmatically or through Interface Builder.

Programmatically

A GAMBannerView can also be instantiated directly. The following example creates a 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

To use a GAMBannerView, create a 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)
  }

To manage the initialization and behavior of the GAMBannerView, create a 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
  }

To get the width of the view, use GeometryReader. This class calculates the appropriate ad size for the current device orientation. The frame is set to the height calculated from the ad size.

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

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

Objective-C

Note that in this case we don't give width or height constraints, as the provided ad size will give the banner an intrinsic content size to size the view.

@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

Interface Builder

You can add a GAMBannerView to a storyboard or xib file. When using this method, be sure to only add position constraints on the banner. For example, when displaying an adaptive banner at the bottom of the screen, set the bottom of the banner view equal to the top of the Bottom Layout Guide, and set the centerX constraint equal to the centerX of the superview.

The banner's ad size is still set programmatically:

Swift

bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

Objective-C

self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);

Load an ad

Once the GAMBannerView is in place and its properties configured, it's time to load an ad. This is done by calling loadRequest: on a GAMRequest object:

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 objects represent a single ad request, and contain properties for things like targeting information.

If your ad fails to load, you don't need to explicitly request another one as long as you've configured your ad unit to refresh; the Google Mobile Ads SDK respects any refresh rate you specified in the Ad Manager UI. If you haven't enabled refresh, you will need to issue a new request.

Ad events

Through the use of GADBannerViewDelegate, you can listen for lifecycle events, such as when an ad is closed or the user leaves the app.

Register for banner events

To register for banner ad events, set the delegate property on GAMBannerView to an object that implements the GADBannerViewDelegate protocol. Generally, the class that implements banner ads also acts as the delegate class, in which case, the delegate property can be set to 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;
}

Implement banner events

Each of the methods in GADBannerViewDelegate is marked as optional, so you only need to implement the methods you want. This example implements each method and logs a message to the console:

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");
}

See the Ad Delegate example for an implementation of banner delegate methods in the iOS API Demo app.

Swift Objective-C

Use cases

Here are some example use cases for these ad event methods.

Add a banner to the view hierarchy once an ad is received

You may want to delay in adding a GAMBannerView to the view hierarchy until after an ad is received. You can do this by listening for the bannerViewDidReceiveAd: event:

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];
}

Animate a banner ad

You can also use the bannerViewDidReceiveAd: event to animate a banner ad once it's returned, as shown in the following example:

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;
  }];
}

Pause and resume the app

The GADBannerViewDelegate protocol has methods to notify you of events, such as when a click causes an overlay to be presented or dismissed. If you want to trace whether these events were due to ads, register for these GADBannerViewDelegate methods.

To catch all types of overlay presentations or external browser invocations, not just those that come from ad clicks, your app is better off listening for the equivalent methods on UIViewController or UIApplication. Here is a table showing the equivalent iOS methods that are invoked at the same time as GADBannerViewDelegate methods:

GADBannerViewDelegate method iOS method
bannerViewWillPresentScreen: UIViewController's viewWillDisappear:
bannerViewWillDismissScreen: UIViewController's viewWillAppear:
bannerViewDidDismissScreen: UIViewController's viewDidAppear:

Manual impression counting

You can manually send impression pings to Ad Manager if you have special conditions for when an impression should be recorded. This can be done by first enabling a GAMBannerView for manual impressions prior to loading an ad:

Swift

bannerView.enableManualImpressions = true

Objective-C

self.bannerView.enableManualImpressions = YES;

When you determine that an ad has been successfully returned and is on screen, you can manually fire an impression:

Swift

bannerView.recordImpression()

Objective-C

[self.bannerView recordImpression];

App events

App events allow you to create ads that can send messages to their app code. The app can then take actions based on these messages.

You can listen for Ad Manager-specific app events using GADAppEventDelegate. These events may occur at any time during the ad's lifecycle, even before the GADBannerViewDelegate object's bannerViewDidReceiveAd: is called.

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;

Your app event methods can be implemented in a view controller:

Swift

import GoogleMobileAds

class ViewController: UIViewController, GADAppEventDelegate {}

Objective-C

@import GoogleMobileAds;

@interface ViewController : UIViewController <GADAppEventDelegate> {}

@end

Remember to set the delegate using the appEventDelegate property before making the request for an ad.

Swift

bannerView.appEventDelegate = self

Objective-C

self.bannerView.appEventDelegate = self;

Here is an example showing how to change the background color of your app by specifying the color through an app event:

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];
    }
  }
}

And, here is the corresponding creative that sends color app event messages to 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>

See the Ad Manager App Events example for an implementation of app events in the iOS API Demo app.

Swift Objective-C

Additional resources

Examples on GitHub

Next steps

Collapsible banners

Collapsible banner ads are banner ads that are initially presented as a larger overlay, with a button to collapse the ad to a smaller size. Consider using it to further optimize your performance. See collapsible banner ads for more details.

Inline adaptive banners

Inline adaptive banners are larger, taller banners compared to anchored adaptive banners. They are of variable height, and can be as tall as the device screen. Inline adaptive banners are recommended over anchored adaptive banner ads for apps that place banner ads in scrollable content. See inline adaptive banners for more details.

Explore other topics