Banner Ads

In the Get Started guide, you learned how to deploy the SDK and display a test banner ad. This guide goes into further customizations that are possible with banner ads.

To see implementations of these banner ad customizations, download the iOS API Demo app in Objective-C or Swift.

Download API Demo

Google Mobile Ads supports the following banner sizes:

Size in points (WxH) Description Availability AdSize Constant
320x50 Standard 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

Smart Banners

Smart Banners are ad units that will render screen-wide 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 phone 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, you will need to use the constant kGADAdSizeSmartBannerPortrait or kGADAdSizeSmartBannerLandscape, like so:

Swift

// Use kGADAdSizeSmartBannerLandscape if your app is running in landscape.
let bannerView = DFPBannerView(adSize: kGADAdSizeSmartBannerPortrait)

Objective-C

// Use kGADAdSizeSmartBannerLandscape if your app is running in landscape.
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 application. The ad size (width, height) defined for an ad request should match the dimensions of the ad view (DFPBannerView) displayed on the application.

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.

Objective-C Swift

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 application, 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: GADBannerView, 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.

Objective-C Swift

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 application code. The application 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 GADBannerViewDelegate's adViewDidReceiveAd: is called.

Swift

// Implement your app event within these methods. 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: GADBannerView,
    didReceiveAppEvent name: String, withInfo info: String?)

// Called when the interstitial receives an app event.
optional public func interstitial(_ interstitial: GADInterstitial,
    didReceiveAppEvent name: String, withInfo info: String?)

Objective-C

// Implement your app event within these methods. 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;
// Called when the interstitial receives an app event.
- (void)interstitial:(DFPInterstitial *)interstitial
    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  {
}

@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 depending on an app event with the name of a color:

Swift

func adView(_ banner: GADBannerView, 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>
    // Send a color=green event when ad loads.
    admob.events.dispatchAppEvent("color", "green");

    handleClick = 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" onClick="handleClick()">Carpe diem!</div>
</body>
</html>

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

Objective-C Swift

Ad lifecycle event callbacks

You may optionally track ad lifecycle events like request failures or "click-through" by implementing all or part of GADBannerViewDelegate.

Swift

public protocol GADBannerViewDelegate : GADAdDelegate {
  optional public func adViewDidReceiveAd(_ bannerView: GADBannerView)
  optional public func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError)
  optional public func adViewWillPresentScreen(_ bannerView: GADBannerView)
  optional public func adViewWillDismissScreen(_ bannerView: GADBannerView)
  optional public func adViewDidDismissScreen(_ bannerView: GADBannerView)
  optional public func adViewWillLeaveApplication(_ bannerView: GADBannerView)
}

Objective-C

@protocol GADBannerViewDelegate 
@optional
- (void)adViewDidReceiveAd:(DFPBannerView *)bannerView;
- (void)adView:(DFPBannerView *)bannerView
    didFailToReceiveAdWithError:(GADRequestError *)error;
- (void)adViewWillPresentScreen:(DFPBannerView *)bannerView;
- (void)adViewDidDismissScreen:(DFPBannerView *)bannerView;
- (void)adViewWillDismissScreen:(DFPBannerView *)bannerView;
- (void)adViewWillLeaveApplication:(DFPBannerView *)bannerView;
@end

These methods may be implemented in either a separate object like a view controller:

Swift

import GoogleMobileAds

class ViewController: UIViewController, GADBannerViewDelegate {
}

Objective-C

@import GoogleMobileAds;

@interface ViewController : UIViewController

@end

or as part of a DFPBannerView subclass:

Swift

import GoogleMobileAds

class MyBannerView: DFPBannerView, GADBannerViewDelegate {
}

Objective-C

@import GoogleMobileAds;

@interface MyBannerView : DFPBannerView

@end

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

Swift

bannerView.delegate = self

Objective-C

self.bannerView.delegate = self;

adViewDidReceiveAd:

Sent when loadRequest: has succeeded. This is a good opportunity to add the sender to the view hierarchy if it has been hidden until now, for example:

Swift

func adViewDidReceiveAd(_ bannerView: GADBannerView) {
  bannerView.hidden = false
}

Objective-C

- (void)adViewDidReceiveAd:(DFPBannerView *)bannerView {
  bannerView.hidden = NO;
}

adView:didFailToReceiveAdWithError:

Sent when loadRequest: has failed, typically because of network failure, an application configuration error, or a lack of ad inventory. You may wish to log these events for debugging:

Swift

func adView(_ bannerView: GADBannerView,
    didFailToReceiveAdWithError error: GADRequestError) {
  print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}

Objective-C

- (void)adView:(DFPBannerView *)adView
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@"adView:didFailToReceiveAdWithError: %@", error.localizedDescription);
}

adViewWillPresentScreen:

Sent immediately before the user is presented with a full-screen ad UI in response to their touching the sender. At this point you should pause any animations, timers or other activities that assume user interaction and save app state, much like on UIApplicationDidEnterBackgroundNotification. Typically the user simply browses the full-screen ad and dismisses it, generating adViewDidDismissScreen: and returning control to your app. If the banner's action was either Click-to-App-Store or Click-to-iTunes or the user presses Home within the ad, however, your app will be backgrounded and potentially terminated.

In these cases under iOS 4.0+, the next method invoked will be your root view controller's applicationWillResignActive: followed by adViewWillLeaveApplication:.

adViewDidDismissScreen:

Sent when the user has exited the sender's full-screen UI.

adViewWillDismissScreen:

Sent immediately before the sender's full-screen UI is dismissed, restoring your app and the root view controller. At this point you should restart any foreground activities paused as part of adViewWillPresentScreen:.

adViewWillLeaveApplication:

Sent just before the application gets backgrounded or terminated as a result of the user touching a Click-to-App-Store or Click-to-iTunes banner. The normal UIApplicationDelegate notifications like applicationDidEnterBackground: arrive immediately before this.

Do not request an ad in applicationWillEnterForeground:, as the request will be ignored. Place the request in applicationDidBecomeActive: instead.

Objective-C delegates are not retained and may be messaged asynchronously before the delegating object is finally deallocated.

See the Ad Delegate example for an implementation of ad lifecycle event callbacks in the iOS API Demo app.

Objective-C Swift

What's next

Send feedback about...

SDK for DFP Users on iOS
Need help? Visit our support page.