Search code examples
iosswiftsprite-kitmopub

Swift: Remove ads different scene in Spritekit


I'm using the MoPub banner ad, I added the following code to my View Controller's viewDidLoad:

     self.adView.delegate = self
    self.adView.frame = CGRectMake(0, self.view.bounds.size.height - MOPUB_BANNER_SIZE.height,
        MOPUB_BANNER_SIZE.width, MOPUB_BANNER_SIZE.height)
    self.view.addSubview(self.adView)
    self.adView.loadAd()

But it makes the ad visible in all the scenes when I only want it to be visible in the main menu scene.

How do I remove the ad in the scenes that I don't want it to be?


Solution

  • This might not be the best way to do this, but it is probably the simplest. You could use an NSNotification to broadcast a message to your ViewController whenever you wish to show or hide you banner.

    For instance if you add an "observer" in your ViewController on init or viewDidLoad:

    NSNotificationCenter.defaultCenter().addObserver(
      self, 
      selector: "hideBannerAd", 
      name: "hideAd", 
      object: nil)
    

    To make the ViewController listen for a message called "hideAd" and then execute a method called hideBannerAd.

    Then implement this method:

    func hideBannerAd(){
      self.adView.hidden = true
    }
    

    Be sure to remove the observer on deinit, this isn't likely to be an issue what with the persistance of a ViewController in SpriteKit but it's good practice.

    deinit{
      NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

    Then, when you want to show or hide the view, for example on a scene transition or game over method, you can implement this hideBannerAd method by triggering the observer using:

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

    And the banner should hide. This can then be repeated for a similar showBannerAd method by setting the hidden property to false, or you can have a single method that simply toggles the hidden property using adView.hidden = !adView.hidden.

    I hope this helps.