Search code examples
iosswiftiad

iAd not working even though I have added the delegate


I am adding an iAd banner and it shows up as a white space whenever I turn the Wi-fi off. I have found similar problems on StackOverflow, with instructions to add a delegate - which I already did. Here is my code:

 func createIAd() {

    bannerView = ADBannerView(adType: .Banner)
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    bannerView.delegate = self
    bannerView.hidden = true
    view.addSubview(bannerView)

    let viewsDictionary = ["bannerView": bannerView]
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bannerView]|", options: [], metrics: nil, views: viewsDictionary))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerView]|", options: [], metrics: nil, views: viewsDictionary))


}

func bannerViewDidLoadAd(banner: ADBannerView!) {

}

func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
    dontShowAd = true
    print("NOAD!!!!")
    hideIAd()
}



func hideIAd() {
    bannerView.hidden = true

}

func showIAd() {
    if dontShowAd == false {
    bannerView.hidden = false
    }
}

Solution

  • Take a look at your code, it says if ADBannerView receives an error don't show ad.

    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
            dontShowAd = true
            print("NOAD!!!!")
            hideIAd()
        }
    

    Turning off your wifi is consider an error because you can't watch or download the add without wifi, think about do you really want your user to have ads displayed on their app when they don't have an internet connection which won't get you any profit because the ad requires wifi in order to work. That's why it's showing you a blank square. But I'm not going to question what you're trying to accomplish, so if you want to display the ad even when the user doesn't have wifi simply change your boolean value to false.

    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
            dontShowAd = false
            print("NOAD!!!!")
            hideIAd()
        }
    

    But If you want to hide the banner when there's no Internet all you have to do is add these 2 functions. Assuming that the connection between the Banner and the ViewController is called Banner. You can get rid of the rest of the code you only

    func bannerViewDidLoadAd(banner: ADBannerView!) {
    
    self.Banner?hidden = false 
    }
    
    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
        self.Banner?hidden true
    }
    }