user6023982 user6023982 - 3 months ago 51
Swift Question

How to show AdMob Interstitial one time on back button tap

I have this code:

func createAndLoadInterstitial() {
interstitial = GADInterstitial(adUnitID: "ca-app-pub-xxxxxxxxxx/xxxxx")
interstitial.delegate = self
let request = GADRequest()
interstitial.loadRequest(request)
}

override func viewDidAppear(animated: Bool) {
if (interstitial.isReady && showAd) {
showAd = false
// print("iterstitialMain is ready")
interstitial.presentFromRootViewController(self)
self.createAndLoadInterstitial()
}
else {
showAd = true
}
}


and it works. But it shows an ad every time the user taps on the back button.

I want to show an ad only one time when the user taps on the back button. Would it be better to show an ad after some time instead? For example, every 5 minutes?

Answer

Where are you setting showAd to true initially? The logic in your if statement is the main issue.

After you set showAd = false in your if statement, the next time viewDidAppear is called your else statement will be executed, setting showAd back to true.

What you should do is check your Bool, and then check interstitial.isReady. Then, in your GADInterstitial's interstitialDidDismissScreen delegate method you would update your showAd Bool and request another GADInterstitial if you'd like. You say you only want to show one GADInterstitial so requesting another is not necessary. For example:

override func viewDidAppear(animated: Bool) {
    if showAd { // Should we show an ad?
        if interstitial.isReady { // Is the ad ready?
            interstitial.presentFromRootViewController(self)
        }
    }
    else {
        // Do nothing
    }
}

func interstitialDidDismissScreen(ad: GADInterstitial!) {
    // Ad was presented and dismissed
    print("interstitialDidDismissScreen")
    showAd = false // Don't show anymore ads
}

Also, you can change:

let request = GADRequest()
interstitial.loadRequest(request)

to just:

interstitial.loadRequest(GADRequest())

in your createAndLoadInterstitial function.

To answer the second part of your question asking if you should present an ad after some time delay, that is a violation of the AdMob program policies:

Examples of non-compliant implementations:

  • Interstitial ads that appear before the app has opened or after the app has closed.
  • Interstitial ads that are triggered after a user closes another interstitial ad.
  • Interstitial ads loading unexpectedly while a user is viewing the app’s content. Remember to only serve interstitials between pages of content.
  • Interstitial ads that trigger after every user click.
  • Interstitial ads that appear during periods of game play or heavy user interaction.