Search code examples
iosswiftsprite-kitiad

How to add iAd in SpriteKit and deactivate it when a scene changes?


In my game file GameScene, I wrote code for iAd to be displayed there.

func addiAd(){
    bannerView = ADBannerView(adType: .Banner)
    bannerView.delegate = self
    bannerView.hidden = true
    bannerView.frame = CGRectOffset(bannerView.frame, 0.0, 0.0)
    bannerView.center = CGPointMake(bannerView.center.x,  
    (view?.bounds.size.height)! - bannerView.frame.size.height/2)
    view!.addSubview(bannerView)
    print("iAd is working")
}

func bannerViewDidLoadAd(banner: ADBannerView!) {
    bannerView.hidden = false
}

func bannerViewActionDidFinish(banner: ADBannerView!) {
    bannerView.removeFromSuperview()
}

func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
    bannerView.hidden = true
}

Well, it first looks like it works, but not perfectly because when a scene has transitioned to another game scene file called GameOverScene, my bannerView does not disappear and stays where it appeared forever until the run is over. I want to deactivate this. Is my code wrong written above? In my source code, in total, I want two adBanner views in GameScene and GameOverScene respectively. My assumption for the error is that I did not write those code in GameViewController, but I am unsure about it. Could you show me how to implement it and explain me where it has to be written?


Solution

  • In the iAd delegate methods you could change the alpha properties of your banner. For example:

    func bannerViewDidLoadAd(banner: ADBannerView!) {
        bannerView.alpha = 1.0
    }
    
    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
        bannerView.alpha = 0.0
    }
    

    And then when you're changing scenes or want to make sure that the iAd banner does not appear you could set its hidden property. For example:

    func hideBanner() {
        // Call whenever you don't want the ADBannerView to be on screen
        bannerView.hidden = true
    }
    
    func showBanner() {
        // Call when you want the ADBannerView to be on screen
        bannerView.hidden = false
    } 
    

    This would require you to update your addiAd function also: Change bannerView.hidden = true to bannerView.alpha = 0.0.

    And finally you shouldn't be removing the iAd banner from the Superview here:

    func bannerViewActionDidFinish(banner: ADBannerView!) {
        bannerView.removeFromSuperview()
    }