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!