class Tools: NSObject, GADBannerViewDelegate {
var view: UIView!
func showAds(viewController: UIViewController) -> Void {
self.view = viewController.view
let request: GADRequest = GADRequest()
request.testDevices = [kGADSimulatorID]
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
bannerView.rootViewController = viewController
bannerView.delegate = self
bannerView.adUnitID = "ca-app-pub-xxx/xxx"
bannerView.loadRequest(request)
}
func adViewDidReceiveAd(bannerView: GADBannerView!) {
self.view.addSubview(bannerView)
}
}
And ViewController class:
class ViewController: UIViewController, GKGameCenterControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Tools().showAds(self)
}
}
class Tools: UIView, GADBannerViewDelegate {
func bannerAdView(viewController: UIViewController) -> UIView {
let request: GADRequest = GADRequest()
request.testDevices = [kGADSimulatorID]
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
addSubview(bannerView)
bannerView.rootViewController = viewController
bannerView.delegate = self
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.loadRequest(request)
return self
}
func adViewDidReceiveAd(bannerView: GADBannerView!) {
print("Reveived Ad : \(bannerView.adNetworkClassName)")
}
}view.addSubview(Tools().bannerAdView(self)) func bannerAdView(viewController: UIViewController) {
let request: GADRequest = GADRequest()
request.testDevices = [kGADSimulatorID]
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
addSubview(bannerView)
bannerView.rootViewController = viewController
bannerView.delegate = self
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.translatesAutoresizingMaskIntoConstraints = false
if let bView = bannerView {
let widthConstraint = NSLayoutConstraint(item: bView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 320)
addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: bView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50)
addConstraint(heightConstraint)
let horizontalConstraint = NSLayoutConstraint(item: bView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
addConstraint(horizontalConstraint)
let bottomConstraint = NSLayoutConstraint(item: bView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
addConstraint(bottomConstraint)
bView.loadRequest(GADRequest())
}
}