You need to create a Singleton class first for which you can follow any of
these patterns. Next import the Mobile Ads framework to write a function to create Banner Ads. Finally in your View Controller, call this function, while sending its residing UIView and make the GADRequest for ads. For example -
class BannerManager: NSObject {
private var bannerView: GADBannerView = GADBannerView()
class var sharedManager: BannerManager {
struct Static {
static var instance: BannerManager?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = BannerManager()
}
return Static.instance!
}
func setupBannerAds(view: UIView) -> GADBannerView {
bannerView.adSize = kGADAdSizeSmartBannerPortrait
view.addSubview(bannerView)
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 320)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50)
view.addConstraint(heightConstraint)
let horizontalConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)
let bottomConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomConstraint)
return bannerView
}
}
class ViewController: UIViewController, GADBannerViewDelegate {
let bManager = BannerManager.sharedManager
override func viewDidLoad() {
super.viewDidLoad()
let banner = bManager.setupBannerAds(view)
banner.delegate = self
banner.rootViewController = self
let request: GADRequest = GADRequest()
request.testDevices = [kGADSimulatorID]
banner.loadRequest(GADRequest())
}
func adViewDidReceiveAd(bannerView: GADBannerView!) {
print("Reveived Ad : \(bannerView.adNetworkClassName)")
}
}