Search code examples
xcodeswiftfacebookadsinterstitial

Why won't my Interstitial Ads work in my GameScene but work in the GameViewController in Swift?


I have these facebook interstitial ads and when I call them in my GameScene they dont show up. They work perfectly when I call them in the GameViewController but not in my GameScene. Can someone tell me what Im doing wrong with my code?

//GameViewController.swift

class GameViewController: UIViewController, FBInterstitialAdDelegate {
let interstitialFBAD: FBInterstitialAd = FBInterstitialAd(placementID: "65543456456456_454345345454534")


override func viewDidLoad() {
    super.viewDidLoad()

}

//CALL THIS IN MY GAMESCENE. 
func loadFBInterstitialAd() {
interstitialFBAD.delegate = self
interstitialFBAD.loadAd()
}

func interstitialAdDidLoad(interstitialAd: FBInterstitialAd!) {
    interstitialFBAD.showAdFromRootViewController(self)
}

//GameScene.swift

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
        let location = touch.locationInNode(self)
        let node = self.nodeAtPoint(location)

        if node.name == "retry" {

            GameViewController().loadFBInterstitialAd()
        }
        }
        }

Solution

  • In viewDidLoad of GameViewController register for a notification, and later from the GameScene post a notification when you want the ad to appear.

    so your viewDidLoad will have the following extra line

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadFBInterstitialAd", name: "loadAd", object: nil)
    

    then write a method in Gamescene

    func showAdNow() {
        NSNotificationCenter.defaultCenter().postNotificationName("loadAd", object: nil)
    }
    

    now in Gamescene.swift replace the line

    GameViewController().loadFBInterstitialAd()
    

    with

    showAdNow()