我希望在多个视图控制器(包括但不限于UITabBarController)中加载 Google Admob Banner View的一个实例。
我的尝试如下。我正在使用AppDelegate设置adSize,adUnitID和testDevices。然后在每个想要显示横幅的VC中,我设置了rootViewController,frame,load request,然后是addSubView。
这很有效,因为广告显示得很好。但是,当我提出或解雇VC时,广告会不断变化!每当VC改变时,似乎都会发生新的请求。 这正是必须避免的结果!
的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 (这有一个通过Push Segue的SecondViewController按钮)
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)
}
}
如何在AppDelegate中创建的一个横幅实例显示在多个 ViewControllers上?感谢。