Tiptonix Beats Tiptonix Beats - 3 months ago 35
iOS Question

Show Interstitial In Other Scenes - Admob, SpriteKit, Swift

How do I show an interstitial ad from admob every x times the user has died or every x times the user does something like presses a button? This is how I showed an interstitial ad on my GameScene and limited ad impressions with a simple if statement.

Answer

This will only work if you have the GoogleMobileAds.sdk and have imported the googlemobileads module into your GameViewController, and GameScene, OR GameOverScene.

I'll be showing you cross-scene ad implementation and programmatically limiting ad impressions.

First, in your GameViewController:

import GoogleMobileAds


class GameViewController: UIViewController, GKLocalPlayerListener, GADInterstitialDelegate {



var myAd = GADInterstitial()


override func viewDidLoad() {
    super.viewDidLoad()


    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.loadAndShow), name: "loadAndShow", object: nil)

}

Create two functions at the bottom of your GameViewController:

func loadAndShow() {



    myAd = GADInterstitial()
    let request = GADRequest()
    myAd.setAdUnitID("ca-app-pub-3940256099942544/4411468910")
    myAd.delegate = self
    myAd.loadRequest(request)



}

func interstitialDidReceiveAd(ad: GADInterstitial!) {

    if (self.myAd.isReady) {

        myAd.presentFromRootViewController(self)



    }



}

You are done with GameViewController. Now head to GameOverScene or GameScene, whatever you need.

Create a global int variable:

var playCount = Int()

In your DidMoveToView say:

playCount = 1

This part is sort of confusing, kinda, not really. Go to your touchesBegan and find where you add actions to a button if it's pressed. For example, a resetGame button resets the scene. Add this there and increment the playButton Int like so:

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches{



        let location = touch.locationInNode(self)
        if resetGame.containsPoint(location) {
            restartScene()

            playCount += 1


        }

Last step. Add these two functions to the bottom of the scene you want to show interstitial ads in:

func displayAd() {



 NSNotificationCenter.defaultCenter().postNotificationName("loadAndShow", object: nil)


}

func checkAd() {


    if playCount % 4 == 0 {

        displayAd()

    }

}

}

Now every fourth time that the user presses the reset game button or dies, an interstitial ad should show up. I hope this helps.

EDIT: I forgot to tell you to call the checkAd() function. Call this function wherever your players dies. So if you have a Bool variable called died or gameover call it in the same spot. For example..

if died == true {
  checkAd()
}