Joyful Games – iPhone game development with Apple’s Swift new language

Email Contact

Play SnakeJoy! The most addicting fun snake game on the internet

Play SnakeJoy in Your Browser!

How to Add Interstitial iAds in SpriteKit with Swift

I recently implemented interstitial iAds for the first time in Swift. I want to share my implementation of interstitial iAds, since I found the current google-sphere a bit lacking (at least in Swift). You’ll need to do some initial work in iTunes Connect to get your iOS app ready for iAds. Once you are ready, you can base your iAds integration on my example.

Implement interstitial iAds into your SpriteKit game

A test interstitial iAd successfully displayed in the iOS emulator

I chose to create a new SKScene to serve as a transition between my menu and game scenes. This transition scene displays the iAd interstitial and uses this time to preload and cache my game textures (the first time through the scene). I attach the iAd interstitial as a sub view on this transition scene’s parent view. We’ll also create our own UIButton to close the interstitial ad, as I show below.

First, import iAd into your file:

import iAd

Second, adhere to the ADInterstitialAdDelegate protocol in your class definition. This allows us to get callbacks after the interstitial iAds close.

class TransitionScene : SKScene, ADInterstitialAdDelegate {

Third, create these properties on the TransitionScene class:

    var interAd:ADInterstitialAd?
    var interAdView = UIView()
    var closeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton

Fourth, configure the close button in the TransitionScene didMoveToView function:

override func didMoveToView(view: SKView) {
    // Define a close button size:
    closeButton.frame = CGRectMake(20, 20, 70, 44)
    closeButton.layer.cornerRadius = 10
    // Give the close button some coloring layout:
    closeButton.backgroundColor = UIColor.whiteColor()
    closeButton.layer.borderColor = UIColor.blackColor().CGColor
    closeButton.layer.borderWidth = 1
    closeButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    // Wire up the closeAd function when the user taps the button
    closeButton.addTarget(self, action: "closeAd:", forControlEvents: UIControlEvents.TouchDown)
    // Some funkiness to get the title to display correctly every time:
    closeButton.enabled = false
    closeButton.setTitle("skip", forState: UIControlState.Normal)
    closeButton.enabled = true
    closeButton.setNeedsLayout()
}

Fifth, implement these functions in your TransitionScene class:

// iAd
func prepareAd() {
    println(" --- AD: Try Load ---")
    // Attempt to load a new ad:
    interAd = ADInterstitialAd()
    interAd?.delegate = self
}

// You can call this function from an external source when you actually want to display an ad:
func showAd() -> Bool {
    if interAd != nil && interAd!.loaded {
        interAdView = UIView()
        interAdView.frame = self.view!.bounds
        self.view?.addSubview(interAdView)
        
        interAd!.presentInView(interAdView)
        UIViewController.prepareInterstitialAds()
        
        interAdView.addSubview(closeButton)
    }
    
    // Return true if we're showing an ad, false if an ad can't be displayed:
    return interAd?.loaded ?? false
}

// When the user clicks the close button, route to the adFinished function:
func closeAd(sender: UIButton) {
    adFinished()
}

// A function of common functionality to run when the user returns to your app:
func adFinished() {
    closeButton.removeFromSuperview()
    interAdView.removeFromSuperview()
    // (Do whatever is next in your app)
}

// The ad loaded successfully (we don't need to do anything for the basic implementation)
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
    println(" --- AD: Load Success ---")
}

// The ad unloaded (we don't need to do anything for the basic implementation)
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
    println(" --- AD: Unload --- ")
}

// This is called if the user clicks into the interstitial, and then finishes interacting with the ad
// We'll call our adFinished function since we're returning to our app:
func interstitialAdActionDidFinish(interstitialAd: ADInterstitialAd!) {
    println(" --- ADD: Action Finished --- ")
    adFinished()
}

func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
    return true
}

// Error in the ad load, print out the error
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
    println(" --- AD: Error --- ")
    println(error.localizedDescription)
}

Sixth, call your new prepareAd function to load a new ad. I’ll often create an instance of the TransitionScene in a separate scene (like my GameScene) so I can load ads before I need to show them (for instance: as soon as the player dies, but before they click new game).

Create an instance of your TransitionScene in the GameScene (or wherever you need it) and then call prepareAd a few moments before you’ll need the transition:

transitionScene.prepareAd()

Finally, in your GameScene (or wherever you are) present the transitionScene instance:

self.view?.presentScene(transitionScene, transition: .crossFadeWithDuration(0.6))

You can call your new showAd function from within the TransitionScene whenever you want the interstitial iAd to show. If you want it to show as soon as the transition scene starts, add the following code to your TransitionScene didMoveToView function:

// Try to show an ad
let adShown = showAd()

// If no ad, just move on
if adShown == false {
    // Do whatever's next for your app
}

I hope that helps you implement interstitial iAds into your SpriteKit Swift app. Leave me a comment if you need any help putting this to use. Cheers!

  • Hi you can help me with this tuto? I already have created the class but wen e call the function showAd() don’t show noting 🙁

    • Stephen Haney

      Hi Pedro – sorry for the slow response. I have been under the weather with a cold and away from the computer! You need to invoke the prepareAd function first, and then wait long enough for it to load an ad before you call showAd. I’ll update the tutorial to reflect this.

      • Sorry but I must be doing something really wrong, you can put the sample in guithub? I think it would be very useful for many people 🙂

        • Stephen Haney

          Sure, that’s a great idea. I’m at work right now but I’ll try to put something together today and reply back. Cheers!

        • Stephen Haney

          Hi Pedro, just wanted to check back in and let you know my work schedule is exploding right now so I won’t be able to move any further on this for a while. Note: I am receiving positive feedback after updating the post above to call the prepareAd function before showAd. Hopefully it will help!

          Best,
          Stephen

          • Sorry but I have little experience in swift and so I am having trouble 😛
            Just to see if I understood. I’ll create a scene (iAD) which is where the iAD will open.Then initialize the scene (iAD) in my opening scene and when I want to show iAD I open this new scene.
            I will not be in the same scene?
            Transit to this new scene iAD.
            That’s it?

          • Stephen Haney

            Hi Pedro – no problem, hope I can help. Your description sounds accurate. You can initialize the next scene you want to show (your iAd scene) within your current scene and then transition to the new scene (iAd) within the code for the current scene. The old scene will be deinit as long as there are no hanging references to it.

  • Michel

    Nothing shows up when you call the function showAd(). What other code is needed?

    • Stephen Haney

      Ah – apologies. You need to invoke the prepareAd function first, and then wait long enough for it to load an ad before you call showAd. I’ll update the tutorial to reflect this.

      • Michel

        Thanks, that worked.

  • Gri Khan

    I don’t get it. Do we need to make new file for this scene and use NSNotifications to perform ads in the scene that we want? Or it should be in the file where we need to perform an ad, like gameoverScene?

    • Stephen Haney

      Hi Gri – you would present this scene whenever you wanted to show the ad. So you could create an instance of TransitionScene in your gameoverScene, then call the transition scene’s prepareAd function from the gameoverScene when you know you are almost ready to show the ad. Then finally present the transition scene (with the showAd() call in the TransitionScene didMoveToView). That’s one possibility that would work well.

      I updated the tutorial above to be more clear about when to transition between scenes.

  • Umut D. Ruffy

    Hi, thanks for this great tutorial! 😀 But I have a problem, when I click “Skip” in my game, it doesn’t show the original scene, it just shows a blank grey screen. Do you know what I did wrong? Like I can’t click anything except my other bannerAd at the bottom, please help 🙂