Banner Ads

Banner ads are rectangular image or text ads that occupy a spot within an app's layout. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. If you're new to mobile advertising, they're a great place to start.

This guide shows you how to integrate banner ads from DFP into an iOS app. In addition to code snippets and instructions, it includes information about sizing banners properly and links to additional resources.

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: /6499/example/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 DFPBannerView

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

Interface Builder

A DFPBannerView can be added to a storyboard or xib file like any typical view. When using this method, be sure to add width and height constraints to match the ad size you'd like to display. For example, when displaying a banner (320x50), use a width constraint of 320 points, and a height constraint of 50 points.

Programmatically

A DFPBannerView can also be instantiated directly. Here's an example of how to create a DFPBannerView, aligned to the bottom center of the safe area of the screen, with a banner size of 320x50:

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  var bannerView: DFPBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    
    // In this case, we instantiate the banner with desired ad size.
    bannerView = DFPBannerView(adSize: kGADAdSizeBanner)

    addBannerViewToView(bannerView)
  }

  func addBannerViewToView(_ bannerView: DFPBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    view.addConstraints(
      [NSLayoutConstraint(item: bannerView,
                          attribute: .bottom,
                          relatedBy: .equal,
                          toItem: bottomLayoutGuide,
                          attribute: .top,
                          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) DFPBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  // In this case, we instantiate the banner with desired ad size.
  self.bannerView = [[DFPBannerView alloc]
      initWithAdSize:kGADAdSizeBanner];

  [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.bottomLayoutGuide
                               attribute:NSLayoutAttributeTop
                              multiplier:1
                                constant:0],
    [NSLayoutConstraint constraintWithItem:bannerView
                               attribute:NSLayoutAttributeCenterX
                               relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                               attribute:NSLayoutAttributeCenterX
                              multiplier:1
                                constant:0]
                                ]];
}
  

@end

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.

If you don't want to use a standard size defined by a constant, you can set a custom size using GADAdSizeFromCGSize. See the banner size section for more information.

Configure DFPBannerView properties

In order to load and display ads, DFPBannerView requires a few properties be set.

  • rootViewController - This view controller is used to present an overlay when the ad is clicked. It should normally be set to the view controller that contains the DFPBannerView.
  • adUnitID - This is the ad unit ID from which the DFPBannerView should load ads.

Here's a code example showing how to set the two required properties in the viewDidLoad method of a UIViewController:

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

Load an ad

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

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  ...

  bannerView.adUnitID = "/6499/example/banner"
  bannerView.rootViewController = self
  bannerView.load(DFPRequest())
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  ...

  self.bannerView.adUnitID = @"/6499/example/banner";
  self.bannerView.rootViewController = self;
  [self.bannerView loadRequest:[DFPRequest request]];
}
DFPRequest objects represent a single ad request, and contain properties for things like targeting information.

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.

Registering for banner events

To register for banner ad events, set the delegate property on DFPBannerView 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: DFPBannerView!

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

Objective-C

@import GoogleMobileAds;

@interface ViewController () <GADBannerViewDelegate>

@property(nonatomic, strong) DFPBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  ...
  self.bannerView.delegate = self;
}

Implementing 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

/// Tells the delegate an ad request loaded an ad.
func adViewDidReceiveAd(_ bannerView: DFPBannerView) {
  print("adViewDidReceiveAd")
}

/// Tells the delegate an ad request failed.
func adView(_ bannerView: DFPBannerView,
    didFailToReceiveAdWithError error: GADRequestError) {
  print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}

/// Tells the delegate that a full-screen view will be presented in response
/// to the user clicking on an ad.
func adViewWillPresentScreen(_ bannerView: DFPBannerView) {
  print("adViewWillPresentScreen")
}

/// Tells the delegate that the full-screen view will be dismissed.
func adViewWillDismissScreen(_ bannerView: DFPBannerView) {
  print("adViewWillDismissScreen")
}

/// Tells the delegate that the full-screen view has been dismissed.
func adViewDidDismissScreen(_ bannerView: DFPBannerView) {
  print("adViewDidDismissScreen")
}

/// Tells the delegate that a user click will open another app (such as
/// the App Store), backgrounding the current app.
func adViewWillLeaveApplication(_ bannerView: DFPBannerView) {
  print("adViewWillLeaveApplication")
}

Objective-C

/// Tells the delegate an ad request loaded an ad.
- (void)adViewDidReceiveAd:(DFPBannerView *)adView {
  NSLog(@"adViewDidReceiveAd");
}

/// Tells the delegate an ad request failed.
- (void)adView:(DFPBannerView *)adView
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@"adView:didFailToReceiveAdWithError: %@", [error localizedDescription]);
}

/// Tells the delegate that a full-screen view will be presented in response
/// to the user clicking on an ad.
- (void)adViewWillPresentScreen:(DFPBannerView *)adView {
  NSLog(@"adViewWillPresentScreen");
}

/// Tells the delegate that the full-screen view will be dismissed.
- (void)adViewWillDismissScreen:(DFPBannerView *)adView {
  NSLog(@"adViewWillDismissScreen");
}

/// Tells the delegate that the full-screen view has been dismissed.
- (void)adViewDidDismissScreen:(DFPBannerView *)adView {
  NSLog(@"adViewDidDismissScreen");
}

/// Tells the delegate that a user click will open another app (such as
/// the App Store), backgrounding the current app.
- (void)adViewWillLeaveApplication:(DFPBannerView *)adView {
  NSLog(@"adViewWillLeaveApplication");
}

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.

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

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

Swift

func adViewDidReceiveAd(_ bannerView: DFPBannerView) {
  // Add banner to view and add constraints as above.
  addBannerViewToView(bannerView)
}

Objective-C

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

Animating a banner ad

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

Swift

func adViewDidReceiveAd(_ bannerView: DFPBannerView) {
  bannerView.alpha = 0
  UIView.animate(withDuration: 1, animations: {
    bannerView.alpha = 1
  })
}

Objective-C

- (void)adViewDidReceiveAd:(DFPBannerView *)adView {
  adView.alpha = 0;
  [UIView animateWithDuration:1.0 animations:^{
    adView.alpha = 1;
  }];
}

Pausing and resuming 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, or invokes an external browser. 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
adViewWillPresentScreen: UIViewController's viewWillDisappear:
adViewWillDismissScreen: UIViewController's viewWillAppear:
adViewDidDismissScreen: UIViewController's viewDidAppear:
adViewWillLeaveApplication: UIApplicationDelegate's applicationDidEnterBackground:

The table below lists the standard banner sizes.

Size in points (WxH) Description Availability AdSize constant
320x50 Banner Phones and tablets kGADAdSizeBanner
320x100 Large banner Phones and tablets kGADAdSizeLargeBanner
300x250 IAB medium rectangle Phones and tablets kGADAdSizeMediumRectangle
468x60 IAB full-size banner Tablets kGADAdSizeFullBanner
728x90 IAB leaderboard Tablets kGADAdSizeLeaderboard
Screen width x 32|50|90 Smart banner Phones and tablets kGADAdSizeSmartBannerPortrait
kGADAdSizeSmartBannerLandscape

Custom ad sizes

To define a custom banner size, set your desired a size using GADAdSizeFromCGSize, as shown here:

Swift

let adSize = GADAdSizeFromCGSize(CGSize(width: 300, height: 50))

Objective-C

GADAdSize size = GADAdSizeFromCGSize(CGSizeMake(300, 50));

Smart Banners

Smart Banners are ad units that render screen-width banner ads on any screen size across different devices in either orientation. Smart Banners help deal with increasing screen fragmentation across different devices by "smartly" detecting the width of the device in its current orientation and making the ad view that size.

Smart Banners on iPhones have a height of 50 points in portrait and 32 points in landscape. On iPads, height is 90 points in both portrait and landscape.

When an image ad isn't large enough to take up the entire allotted space, the image will be centered, and the space on either side will be filled in.

To use Smart Banners, just specify kGADAdSizeSmartBannerPortrait (for portait orientation) or kGADAdSizeSmartBannerLandscape (for landscape orientation) for the ad size:

Swift

let bannerView = DFPBannerView(adSize: kGADAdSizeSmartBannerPortrait)

Objective-C

DFPBannerView *bannerView = [[DFPBannerView alloc]
      initWithAdSize:kGADAdSizeSmartBannerPortrait];

Custom ad size

In addition to the standard ad units, DFP allows you to serve any sized ad unit into an app. The ad size (width, height) defined for an ad request should match the dimensions of the ad view (DFPBannerView) displayed on the app. To set a custom size, use GADAdSizeFromCGSize.

Swift

// Define custom GADAdSize of 250x250 for DFPBannerView.
let customAdSize = GADAdSizeFromCGSize(CGSize(width: 250, height: 250))
bannerView = DFPBannerView(adSize: customAdSize)

Objective-C

// Define custom GADAdSize of 250x250 for DFPBannerView
GADAdSize customAdSize = GADAdSizeFromCGSize(CGSizeMake(250, 250));
self.bannerView = [[DFPBannerView alloc] initWithAdSize:customAdSize];

See the DFP Multiple Ad Sizes example for an implementation of custom ad size in the iOS API Demo app.

Swift Objective-C

Multiple ad sizes

DFP allows you to specify multiple ad sizes which may be eligible to serve into a DFPBannerView. There are three steps needed in order to use this feature:

  1. In the DFP UI, create a line item targeting the same ad unit that is associated with different size creatives.

  2. In your app, set the validAdSizes property on DFPBannerView:

    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 kGADAdSizeBanner), or create one using
    // the GADAdSizeFromCGSize method.
    //
    // Note: Ensure that the allocated DFPBannerView is defined with an ad size. Also note
    // that all desired sizes should be included in the validAdSizes array.
    bannerView.validAdSizes = [NSValueFromGADAdSize(kGADAdSizeBanner),
        NSValueFromGADAdSize(kGADAdSizeMediumRectangle),
        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 kGADAdSizeBanner), or create one using
    // the GADAdSizeFromCGSize method.
    //
    // Note: Ensure that the allocated DFPBannerView is defined with an ad size. Also note
    // that all desired sizes should be included in the validAdSizes array.
    self.bannerView.validAdSizes = @[
        NSValueFromGADAdSize(kGADAdSizeBanner),
        NSValueFromGADAdSize(kGADAdSizeMediumRectangle),
        NSValueFromGADAdSize(GADAdSizeFromCGSize(CGSizeMake(120, 20)))
    ];
    

  3. Implement the GADAdSizeDelegate method to detect an ad size change.

    Swift

    public func adView(_ bannerView: DFPBannerView, willChangeAdSizeTo size: GADAdSize)
    

    Objective-C

    - (void)adView:(DFPBannerView *)view willChangeAdSizeTo:(GADAdSize)size;
    

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

    Swift

    bannerView.adSizeDelegate = self

    Objective-C

    self.bannerView.adSizeDelegate = self;

See the DFP Multiple Ad Sizes example for an implementation of custom ad size in the iOS API Demo app.

Swift Objective-C

Manual impression counting

You can manually send impression pings to DFP if you have special conditions for when an impression should be recorded. This can be done by first enabling a DFPBannerView 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 DFP specific app events using GADAppEventDelegate. These events may occur at any time during the ad's lifecycle, even before the GADBannerViewDelegate object's adViewDidReceiveAd: 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 adView(_ banner: DFPBannerView,
    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)adView:(DFPBannerView *)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 adView(_ banner: DFPBannerView, 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)adView:(DFPBannerView *)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="//media.admob.com/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 DFP App Events example for an implementation of app events in the iOS API Demo app.

Swift Objective-C

Additional resources

Samples on GitHub

Mobile Ads Garage video tutorials

Next steps

Send feedback about...

Google Mobile Ads SDK for DoubleClick for Publishers iOS Apps
Need help? Visit our support page.