Summary

Using Smart Banners in iOS10 Universal Apps using Adaptive Layout (Swift 3)

This implementation will automatically adjust the banner to fit the current orientation of the device

Swift

import UIKit
import GoogleMobileAds

class ViewController: UIViewController {

    let bannerView: GADBannerView = GADBannerView.init(adSize: kGADAdSizeSmartBannerPortrait)

    override func viewDidLoad() {
        super.viewDidLoad()

        setupAdBanner()

    }

    // Mark: Google Ad's
    func setupAdBanner() {
        // set the banner orientation when the view loads
        let currentDevice: UIDevice = UIDevice.current
        let orientation: UIDeviceOrientation = currentDevice.orientation

        if orientation.isLandscape {
            setBannerOrientation(portrait: false)
        }

        // Load an ad in the usual way
        print("Google Mobile Ads SDK version: " + GADRequest.sdkVersion())
        bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        bannerView.rootViewController = self
        bannerView.load(GADRequest())

        self.bannerView.translatesAutoresizingMaskIntoConstraints = false

        // create contraints to centre the add and pin to the bottom of the view
        let xConstraint = NSLayoutConstraint(item: bannerView, attribute: .centerX,
                                             relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)

        let pinBottom = NSLayoutConstraint(item: bannerView, attribute: .bottom,
                                           relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)

        // must add to sub view prior to adding constraints
        self.view.addSubview(bannerView)

        self.view.addConstraint(xConstraint)
        self.view.addConstraint(pinBottom)
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

        super.viewWillTransition(to: size, with: coordinator)

        // detect orientation change and adjust banner accordinly
        if UIDevice.current.orientation.isLandscape {
            setBannerOrientation(portrait: false)
        } else {
            setBannerOrientation(portrait: true)
        }
    }

    func setBannerOrientation( portrait: Bool ){
        if portrait {
            self.bannerView.adSize = kGADAdSizeSmartBannerPortrait;
        } else {
            // Landscape
            self.bannerView.adSize = kGADAdSizeSmartBannerLandscape;
        }
    }
}
                    

View full project in GitHub