Swift: Regulating The Number of Interstitial Ads in App

Greetings! (I am hoping this is the right place to ask this/marked as a question)
I have recently tried stack overflow for this problem, but I haven't been seeing any success.
I hope for more luck here!


As the title suggests, I wish to limit the number of AdMob insterstitial ads in my Swift iOS app. Basically, I have an app that is a bunch of text and buttons, so I'm using button actions to control interstitial placements.



Here is my interstitial ad criteria:

  1. Have an interstitial ad show after 3 button clicks on a page
  2. If an interstitial ad shows up, no interstials may show for the entire app until 3 minutes are up.

I've done as much research as I can, but I'm still at a loss on how I can achieve these results. I'm not much of a programmer, but I am trying my best!

Here is my current swift code, my apologies for the visual formatting, I tried to make it as eye-pleasing as possible.


The swift code below simply makes interstitials pop up at every button click (along with banner ads loaded in):

________________________________________________________________


import UIKit

import GoogleMobileAds


class ViewControllerInterstitial: UIViewController {

var interstitial: GADInterstitial!


@IBOutlet var BannerView: GADBannerView!

@IBOutlet var ScrollViewInterstitial: UIScrollView!


override func viewDidLoad() {

super.viewDidLoad()

self.BannerView.adUnitID = "ca-app-pub-XXXXXXXXX/XXXXXXX"


self.BannerView.rootViewController = self

var request: GADRequest = GADRequest()

request.testDevices = [ kGADSimulatorID ]


self.BannerViewI.loadRequest(request)

self.interstitial = self.createAndLoadAd()

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()


}


//Loading Interstitial

func createAndLoadAd() -> GADInterstitial


{


var ad = GADInterstitial(adUnitID: "ca-app-pub-XXXXXXXXXXX/XXXXXXXXX")

var request = GADRequest()


request.testDevices = [kGADSimulatorID]

ad.loadRequest(request)


return ad


}


// BUTTON ACTION: This is where I assume I could apply the counter criteria


@IBAction func adButton(sender: AnyObject)


{


if (self.interstitial.isReady)


{

self.interstitial.presentFromRootViewController(self)

self.interstitial = self.createAndLoadAd()


}


}


// BUTTON ACTION 2: process is repeated once more for 2nd button (and so on and so forth with more buttons)


@IBAction func adButton2 (sender: AnyObject)

{


if (self.interstitial.isReady)


{

self.interstitial.presentFromRootViewController(self)

self.interstitial = self.createAndLoadAd()


}


}



______________________________________________________________


Just for some extra detail if this makes things easier, I have accomplished this particular feat in Java


If you were curious, the Java code is below:


______________________________________________________________


public class InterstitialPage extends Activity {


// Here is where I set up my interstitial counter

// So each time you arrive to this page, the counter will be zero


private InterstitialAd interstitial;

private int counter = 0;


//End the interstitial counter



// Here I have code for content views, preparing the interstitial ad, ad IDs, test devices, blah blah.

// Taken out because it's not important.



// Here is my on click listener, which helps me go from one class to the other.

// HOWEVER, I am able to set a counter inside of the on click listener shown below:


cp1.setOnClickListener(new View.OnClickListener() {


@Override public void onClick(View v) {

startActivity(new Intent(InterstitialPage.this, InterstitialSubPage1.class));

// Very Important Here: the counter function

counter++;

displayInterstitial();

//Ending the counter function

}

});


//A Second time (repeated multiple times for multiple buttons)


cp2.setOnClickListener(new View.OnClickListener() {


@

Override

public void onClick(View v) {

startActivity(new Intent(InterstitialPage.this, Commonproblem2class.class));


//Counter

counter++;

displayInterstitial();

//End Counter

}

});


//How I got all of the interstitial ads in Java to "connect" with one another: by using a key in SharedPreferences


private static String LAST_INTERSTITIAL_DATE_KEY = "lastInterstitialDate";

private void displayInterstitial() {


SharedPreferences prefs = this.getSharedPreferences(

"com.author.title", Context.MODE_PRIVATE);

long x = prefs.getLong(LAST_INTERSTITIAL_DATE_KEY, 0);

System.out.println("_____fecha de pref" + x);


//Where the 3 minutes and 3 click counter comes together


if (x < System.currentTimeMillis() - 3 * 60 * 1000)

if (interstitial.isLoaded() && counter >= 3) {


Editor editor = prefs.edit();

editor.putLong(LAST_INTERSTITIAL_DATE_KEY, System.currentTimeMillis());

editor.commit();


interstitial.show();

loadInterstitial();

}

}

// END SHARED PREFERENCES


private void loadInterstitial()

______________________________________________________________


I hope this is enough info to make this problem a simple fix.
Any advice is greatly appreciated! Thank you for viewing!

(untested other than compiles without error in Xcode 7 beta 3)

let clickCountToTriggerAd = 3
let minimumTimeBetweenAds: NSTimeInterval = 180   // in seconds

let sharedAdLimiter = AdLimiter()

class AdLimiter
{
    static var sharedInstance: AdLimiter {return sharedAdLimiter}

    weak var lastViewController: UIViewController? = nil
    var count = 0
    var timeLastShown: NSDate? = nil

    func shouldDisplayAdForClickFromController(source: UIViewController) -> Bool
    {
        if (source === lastViewController) {++count}
        else
        {
            lastViewController = source
            count = 1
        }
     
        if (count >= clickCountToTriggerAd)
        {
            if let last = timeLastShown where (abs(last.timeIntervalSinceNow) < minimumTimeBetweenAds) {return false}
         
            // will display ad
            count = 0
            timeLastShown = NSDate()
            return true
        }
        else {return false}
    }
}


in your button actions

let shouldShowAd: Bool = AdLimiter.sharedInstance.shouldDisplayAdForClickFromController(self)

Thank you for the reply LCS!


However, my code is still preforming the same way as it did before, unfortunately.
My best guess is: the 34 lines of code should go under "imports" and the 1 line of code should go under each "@IBAction func { " of each button, but nothing has really changed.
I've been trying other placements too, but I haven't seen any luck.


If you believe I am doing something wrong or if you see the problem, I would definitely appreciate it!
In the meantime, I will be researching as much as I can to see if I can get anywhere.
Also thank you for giving me a code to start with so that I actually have something to work with! It's a lot better than going mindlessly through it haha

The AdLimiter code (the 34 lines can be in its own file, and doesn't need to be imported since Swift code within the same project is automatically available.


The other one line creates a true/false Bool of whether the ad should be displayed, and should go in each IBAction to wrap the code to display the ad.


if (AdLimiter.sharedInstance.shouldDisplayAdForClickFromController(self))
{
     // display ad
     if (self.interstitial.isReady)
     {   
          self.interstitial.presentFromRootViewController(self)
          self.interstitial = self.createAndLoadAd()
     }
}

I didn't read all the thing you posted, but You can use NSTimer() to call a function every 3 minutes or so, in order to only active your ads when 3 minutes are over. Dunno, how much help that is. Also, personally, when i researched, i have found that reviews about admob say that it don't pay much. Infact Admobs generate such less eCPM that its ridiculous...

Swift: Regulating The Number of Interstitial Ads in App
 
 
Q