问题
I am implementing an AdMob banner in my app for a single UIViewController
, and it is working. But I have so many views and I want to show a banner on every screen. How would I implement a banner that would appear on every screen? I am trying this in my AppDelegate.swift
:
dispatch_async(dispatch_get_main_queue(), {
print("Google Mobile Ads SDK version: \(GADRequest.sdkVersion())")
// bannerView.frame = CGRectMake(0, 0, 320, 50)
// self.bannerView.adSize = kGADAdSizeBanner
self.bannerView.adUnitID = "ca-app-pub-MY_ID"
bannerView.rootViewController = self.window
self.bannerView.loadRequest(GADRequest())
self.window?.addSubview(self.bannerView)
})
but its not working
回答1:
Create a shared banner. You init
it in your AppDelegate
and then add it to the UIViewController
's that you'd like to have a banner on:
class AppDelegate: UIResponder, UIApplicationDelegate, GADBannerViewDelegate {
var window: UIWindow?
var adBannerView = GADBannerView()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
adBannerView.adUnitID = "YourAdUnitID"
adBannerView.delegate = self
adBannerView.load(GADRequest())
adBannerView.isHidden = true
return true
}
func adViewDidReceiveAd(_ bannerView: GADBannerView!) {
adBannerView.isHidden = false
}
func adView(_ bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {
adBannerView.isHidden = true
}
In each UIViewController
you'd like to have a banner:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
addBannerToView()
}
func addBannerToView() {
appDelegate.adBannerView.adSize = kGADAdSizeBanner
appDelegate.adBannerView.rootViewController = self
appDelegate.adBannerView.frame = CGRect(x: 0.0,
y: view.frame.height - appDelegate.adBannerView.frame.height,
width: view.frame.width,
height: appDelegate.adBannerView.frame.height)
view.addSubview(appDelegate.adBannerView)
}
回答2:
SWIFT 3
func showAds(viewAds:GADBannerView,viewController:UIViewController){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.adBannerView.adSize = kGADAdSizeBanner
appDelegate.adBannerView.rootViewController = viewController
appDelegate.adBannerView.frame = CGRect(x: 0,
y: 0,
width: viewAds.frame.width,
height: viewAds.frame.height)
viewAds.addSubview(appDelegate.adBannerView)
}
showAds(viewAds: adseHere, viewController: self)
来源:https://stackoverflow.com/questions/39572974/how-to-add-an-admob-gadbannerview-to-every-view