user11768919
user11768919

Reputation:

How can I make an interstitial ad that only shows 20% of the time?

I want to only display an interstitial ad 20% of the time. So that 20% that I use the swipe gesture an ad is displayed. In the code you see below I deleted all the unnecessary code so you only see code related to the ad.

import UIKit
import GoogleMobileAds
class allaBarnen: UIViewController {

     var interstitial: GADInterstitial!


    override func viewDidLoad() {
        super.viewDidLoad()
        let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
        leftSwipe.direction = UISwipeGestureRecognizer.Direction.left
        self.view.addGestureRecognizer(leftSwipe)




        //create interstitial
        interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")

        let request = GADRequest()
        interstitial.load(request)
    }
    @objc func swipeAction(swipe:UISwipeGestureRecognizer){

        //uses interstitial 
        if interstitial.isReady {
            interstitial.present(fromRootViewController: self)      

        interstitial = createAd()

        } 
             }

//reuses interstitial so that it can display again func createAd() -> GADInterstitial {

      let inter = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")

        inter.load(GADRequest())
        return inter
    }

}

Upvotes: 1

Views: 26

Answers (1)

Sweeper
Sweeper

Reputation: 271185

Just before you show the ad, generate a random number between 0 and 100, and check if it is less than 20:

if interstitial.isReady && Int.random(in: 0..<100) < 20 {
    interstitial.present(fromRootViewController: self) 
    ...

Upvotes: 1

Related Questions