简体   繁体   中英

Hide Admob Ads programmatically with Swift

My admob ads is loaded from viewDidLoad

override func viewDidLoad() {
        super.viewDidLoad()
            let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
            bannerView.frame = CGRect(x: 0.0,
                                      y: UIApplication.sharedApplication().statusBarFrame.size.height,
                                      width: bannerView.frame.width,
                                      height: bannerView.frame.height)
            bannerView.adUnitID = "ca-app-pub-myID"
            bannerView.rootViewController = self
            bannerView.loadRequest(GADRequest())
            view.addSubview(bannerView)
    }

I am trying to do a function to hide the ads using:

func removeAds () {
        let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        bannerView.removeFromSuperview()
    }

However, this is not working. What's wrong did I made?

You are creating entirely new instance of AdView here

func removeAds () {
        let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        bannerView.removeFromSuperview()
    }

You need to define you instance of AdView Globally for the Current Class above view did load

You can achive this with code below

var bannerView : GADBannerView!

override func viewDidLoad() {
        super.viewDidLoad()
           bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
            bannerView.frame = CGRect(x: 0.0,
                                      y: UIApplication.sharedApplication().statusBarFrame.size.height,
                                      width: bannerView.frame.width,
                                      height: bannerView.frame.height)
            bannerView.adUnitID = "ca-app-pub-myID"
            bannerView.rootViewController = self
            bannerView.loadRequest(GADRequest())
            view.addSubview(bannerView)
    }

and you can remove that addView with

func removeAds () {
        bannerView.removeFromSuperview()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM