VIẾT NAM
VIẾT NAM

Reputation: 135

IOS admob with Swift in SpriteKit

I have followed the Documentation that I found (googleAd in swift). when I performed in my SpriteKit scene. Command line "bannerView? .rootViewController = Self" appear error.

gamescene not convertible to UIViewController

 bannerView = GADBannerView(adSize: kGADAdSizeBanner)
            bannerView?.adUnitID = "xxxxxxxxxxxxxxxxxxxxx"
            bannerView?.delegate = self
            bannerView?.rootViewController = self // -> Error "gamescene not convertible to UIViewController"
            self.view?.addSubview(bannerView!)
            bannerView?.loadRequest(GADRequest())

            timer?.invalidate()
            timer = NSTimer.scheduledTimerWithTimeInterval(40, target: self, selector: "GoogleAdRequestTimer", userInfo: nil, repeats: true)

Upvotes: 3

Views: 3118

Answers (1)

PoisonedApps
PoisonedApps

Reputation: 726

You need to put this code in viewDidLoad within GameViewController.swift not in GameScene.swift.

Remember to add GADBannerViewDelegate to the class.

Example:

class GameViewController: UIViewController, GADBannerViewDelegate {

var scene: GameScene!
var adBannerView: GADBannerView!

override func viewDidLoad() {
    super.viewDidLoad()

        // Configure the view.
        let skView = view as SKView
        skView.showsFPS = false
        skView.showsNodeCount = false
        skView.showsPhysics = false

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene = GameScene(size: skView.bounds.size)
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)

    adBannerView = GADBannerView(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
    adBannerView.delegate = self
    adBannerView.rootViewController = self
    adBannerView.adUnitID = "YOUR AD ID"

    var reqAd = GADRequest()
    reqAd.testDevices = [GAD_SIMULATOR_ID] // If you want test ad's
    adBannerView.loadRequest(reqAd)
    self.view.addSubview(adBannerView)


}

I have referenced two links that provide examples on how to include Google Ad's (AdMob) into an app.

Google Ad's with Swift Example 1 (more detailed)

Google Ad's with Swift Example 2

I hope this helps

Upvotes: 4

Related Questions