I am looking to load one instance of a Google Admob Banner View throughout multiple View Controllers (including, but not limited to a UITabBarController.)
My attempt is below. I'm using AppDelegate to set the adSize, adUnitID and testDevices. Then in each VC where I want a banner displayed, I set the rootViewController, frame, load request, and then addSubView.
This works, in the fact that the ads show up fine. However, the ads keep changing when I segue or dismiss VC! It appears that a new request is happening everytime VC's change. Which is precisely the result that must be avoided!
AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var adBannerViewFromAppDelegate = GADBannerView()
let loadRequest = GADRequest()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
adBannerViewFromAppDelegate.adSize = kGADAdSizeSmartBannerPortrait
adBannerViewFromAppDelegate.adUnitID = "12345"
loadRequest.testDevices = [kGADSimulatorID, myiPhone]
}
}
ViewController (This has a button to SecondViewController via Push Segue)
import UIKit
import GoogleMobileAds
class ViewController: UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addBannerToView()
}
func addBannerToView() {
appDelegate.adBannerViewFromAppDelegate.rootViewController = self
appDelegate.adBannerViewFromAppDelegate.load(appDelegate.loadRequest)
appDelegate.adBannerViewFromAppDelegate.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: appDelegate.adBannerViewFromAppDelegate.frame.height)
view.addSubview(appDelegate.adBannerViewFromAppDelegate)
}
}
SecondViewController
import UIKit
import GoogleMobileAds
class SecondViewController: UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addBannerToView()
}
@IBAction func closeButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
func addBannerToView() {
appDelegate.adBannerViewFromAppDelegate.rootViewController = self
appDelegate.adBannerViewFromAppDelegate.load(appDelegate.loadRequest)
appDelegate.adBannerViewFromAppDelegate.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: appDelegate.adBannerViewFromAppDelegate.frame.height)
view.addSubview(appDelegate.adBannerViewFromAppDelegate)
}
}
How can I get one instance of the Banner created in the AppDelegate to display on multiple ViewControllers? Thanks.