Integrate Adaptive Banner with Xcode

229a60ff96296b2e.png

Last Updated: 2020-01-10

Adaptive banners are the next generation of responsive ads, maximizing performance by optimizing ad size for each device. Improving on smart banners, which only supported fixed heights, adaptive banners let developers specify the ad width and use this to determine the optimal ad size.

AdMob supports Adaptive Banners by providing the Adaptive Banner API—a new way to request banner ads, and it only requires minimal changes from the existing banner ads API. In this new API, publishers requesting an Adaptive Banner ad specify the maximum available width for ads in the given placement, and pass this width to the banner ad request. AdMob then chooses the optimal banner creative for the device requesting the ad and the space available, aiming to maximize revenue performance and fill the available space.

This codelab will walk you through integrating an Adaptive Anchor banner into a new application. You'll start with an empty app created by Xcode with no ads. Over the course of the codelab, you'll install the AdMob SDK, prepare your layout, and add code to load and display an Adaptive Anchor banner.

What you'll build

In this codelab, you're going to create a new blank application and then implement an Adaptive Anchor banner using the Swift language

What you'll learn

  • How to install the AdMob SDK in your application.
  • How to integrate an Adaptive Anchor Banner with your application.
  • How to set a background to your banner view..

What you'll need

  • A recent version of Xcode (11.x+)

Create a new Xcode project

  1. Create a new project in Xcode.
  2. Choose the Single View App template.
  3. Choose the language as Swift and Storyboard for User Interface.

d0e8c896cb242b09.png

49fa69d54e7ba0a1.png

30a335cb9433f506.png

Add the Mobile Ads SDK to your project gradle file

There are two different ways to import the Mobile Ads SDK to your project. You can either use CocoaPods or manually download and import the SDK. If you are familiar with CocoaPods, please follow this guide to automatically import the SDK. In this tutorial I will show you how to do it manually.

  1. Download and unzip the SDK framework
  2. Import the following frameworks into your Xcode project:
  • GoogleMobileAds.framework
  • GoogleAppMeasurement.framework
  • GoogleUtilities.framework
  • Nanopb.framework

9f363e25cec77d01.png

  1. Add the -ObjC linker flag to Other Linker Flags in your project's build settings

7da9601671b38103.png

Update your Info.plist

Add your AdMob App ID to your app's Info.plist file by adding the GADApplicationIdentifier key with a string value of your App ID as shown below. You can find your App ID in the AdMob UI a9b25b7ce08338e8.png

For the purpose of this codelab, you can use the sample App ID shown above (ca-app-pub-3940256099942544~1458002511). In a production app, you would Set up an app in AdMob and find your app ID in the AdMob UI.

Import the GoogleMobileAds framework

To be able to use the MobileAds API, you need to import the framework.

Add the following line at the top of your AppDelegate.swift file:

import GoogleMobileAds

Initialize the Mobile Ads SDK

In order to use the Mobile Ads SDK, you need to initialize it. This needs to be done only once, ideally at app launch.

  1. In your AppDelegate.swift's application(_ didFinishLaunchingWithOptions:) method, call the start(completionHandler:) method on the GADMobileAds.sharedInstance, which initializes the SDK and calls back a completion listener once initialization is complete (or after a 30-second timeout). It is not necessary to wait for the completion handler for our use case.
  2. If you're using mediation, you may wish to wait until the completion handler is called before loading ads, as this will ensure that all mediation adapters are initialized.
  3. Now you can try to build & run your project to check if there is any issue.
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication,
         didFinishLaunchingWithOptions launchOptions:
         [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        return true
    }

You can create and render a banner ad in your iOS app by using the GADBannerView. This can be done by using either Interface Builder or Programmatically. In this codelab, we will create the banner in code and align it to the bottom center of the safe area of the screen.

  1. In ViewController.swift, import GoogleMobileAds
  2. Define a variable bannerView of type GADBannerView and init it
  3. In the viewDidLoad function, set your AdMob Ad Unit ID to your GADBannerView by using the adUnitID property of the bannerView object. Again, for this example, you can use AdMob's test ad unit
import GoogleMobileAds
import UIKit

class ViewController: UIViewController {
    let bannerView = GADBannerView()
    
    override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
       bannerView.adUnitID = "ca-app-pub-3940256099942544/2435281174"  
       bannerView.rootViewController = self
    }
  1. Create function addBannerToView() to add your banner object into the current view:
func addBannerToView(){
        bannerView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(bannerView)
        
        NSLayoutConstraint.activate([
            //align your banner to the bottom of the safe area
            bannerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            //Center your banner horizontally
            bannerView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }
  1. Call the function addBannerToView() in the viewDidLoad() function. Now you are done creating and adding the banner to your view.
    bannerView.adUnitID = "ca-app-pub-3940256099942544/2435281174"
    bannerView.rootViewController = self
    addBannerToView();
}

There are three methods to get the ad size for an Adaptive Banner—one for landscape, one for portrait, and one for the current orientation at the time of execution. You provide your preferred width, and then the API will return the optimal size for the banner ad on the device running the app.

The Adaptive Banner sizes are designed to work best when using the full available width. In most cases, this will be the full width of the screen of the device in use. In this example, you will use the full width of the device for your banner.

Create a function to get the Adaptive Size

First, you need to define the width you want to use (in point). Adaptive Banner APIs provide three APIs for you to get the optimal size depended on your orientation:

  • GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth()
  • GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth()
  • GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth()

GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth() is easy to use as it auto-detects the device's current orientation and returns the corresponding AdSize. But if you want to preload in advance a banner in a specific orientation, then you can use the other APIs.

Use GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth() to build our function getAdaptiveSize which return the adaptive size for banners:

 func getAdaptiveSize() -> GADAdSize {
        // Step 1 - Determine the view width to use for the ad width.
        //in this codelab we use the full safe area width
        var frame: CGRect
        // Here safe area is taken into account, hence the view frame is used
        // after the view has been laid out.
        if #available(iOS 11.0, *) {
            frame = view.frame.inset(by: view.safeAreaInsets)
        } else {
            frame = view.frame
        }
        let viewWidth = frame.size.width

        // Step 2 - Get Adaptive GADAdSize and set the ad view.
        let adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
        return adSize
    }

Create a function to request your banner ads

Now, you are finally ready to load and show off your banner...

After having the size, you can create the function loadBanner() in your ViewController.swift to request your banner by calling the load() function from your bannerView object:

func loadAdaptiveBannerAd(){
      bannerView.adSize = getAdaptiveSize()
      bannerView.load(GADRequest())
}

Start requesting your Adaptive banner

Now in the viewDidAppear() function of your ViewController.swift, after creating your BannerView and setting an ad unit to it, you can request a banner with adaptive size. Your banner will be shown automatically after an ad is returned.

Note loadBannerAd() is called in viewDidAppear() as this is the first time that the safe area is known. If the safe area is not a concern (e.g., your app is locked in portrait mode), the banner can be loaded in viewWillAppear().

override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
      loadAdaptiveBannerAd()
}

Build and run your app to see the banner:

9ad83ac900894e47.png

Handling the overlapping with app content issue

Even if you use the full device screen width for your banner, there is still a chance that the returned creative (the actual ad) has a smaller size than your provided size. In this case AdMob SDK will try to scale the creative to fit the size while maintaining its ratio. This may create blank spaces as shown in the following screenshot:

9d92b929517b6fa8.png

This can create an ‘overlapping with app content' issue, where the ad obscures content from the user. To avoid that, you need to create a background that covers the whole banner size to make sure there will be no app content in the banner area.

Create a background

In the production app, you should create a nice background with the color matching with your application UI/UX. In this example, we can test the background by setting the background color of your bannerView, since it is a subclass of UIView. If the returned creative is smaller than the GADBannerView's frame, the background color will be visible around the border of the creative.

We can do this by setting the backgroundColor property of the bannerView object. You can try to set it to darkGray color as shown below:

override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view.
       bannerView.adUnitID = "ca-app-pub-3940256099942544/2435281174"
       bannerView.rootViewController = self
       bannerView.backgroundColor = .darkGray
       addBannerToView()
}

Your result will look like this:

830d3afdd6347063.png

Congratulations, your app now is ready to display Adaptive Anchor Banners!

What we've covered

  • How to install the Google Mobile Ads SDK.
  • How to create and display Adaptive Banners.
  • How to create a background to cover the whole banner size.

Next steps

Learn more