Reputation: 713
I am trying to add a interstitial ad in a Swift SpriteKit game and most of the problems/soultions I see are related to the banner view and not the interstitial display of the admob ads.
What I did was adding all the frameworks and the sample code from google like described here Adding interstitial ads to your project into my GamveViewController.swift
import UIKit
import GoogleMobileAds
class ViewController: UIViewController {
var interstitial: GADInterstitial!
override func viewDidLoad() {
super.viewDidLoad()
interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
let request = GADRequest()
// Requests test ads on test devices.
request.testDevices = ["2077ef9a63d2b398840261c8221a0c9b"]
interstitial.loadRequest(request)
}
}
Then I want to call the function to display the ad in my GameScene.swift and this leads to an error and I dont know why
if (self.interstitialAd.isReady) {
self.interstitialAd.presentFromRootViewController(self)
}
The error codes I get are: 1. "use of undeclared type "GADInerstittial" 2."GameScene has no member interstitial
It seems I need to connect my GameViewController and the Game Scene, but I do not know how. Anyone with a helping hand?
Upvotes: 1
Views: 800
Reputation: 10674
You cannot just present the ad in a gameScene, you need a viewController.
The easiest way is to put the code from GameScene into your ViewController.
So move/or create a func in ViewController like so
func showInterAd() {
/// code to present inter ad
}
Than you can use something like NSNotificationCenter to forward the message from GameScene to the ViewController.
Still in your ViewController add an observer in viewDidLoad
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showInterAd), name: "ShowAd", object: nil)
Than in your GameScene when you want to show the ad post the notification.
NSNotificationCenter.defaultCenter().postNotificationName("ShowAd", object: nil)
Alternatively I have a helper on gitHub if you want a cleaner and more reusable solution
https://github.com/crashoverride777/Swift-iAds-AdMob-CustomAds-Helper
Upvotes: 1