如何在Sprite Kit中显示弹出式插页式广告?

时间:2017-04-13 03:54:05

标签: ios swift sprite-kit

我想在玩家死后在我的应用上显示插页式广告。我在ViewController中有它的功能,但我不知道如何在GameScene中使用它。我在View Controller中有以下代码:

import UIKit
import SpriteKit
import GameplayKit
import GoogleMobileAds

protocol AdMobInterstitialDelegate{
    func createInterstitialAd()
}


class GameViewController: UIViewController, GADBannerViewDelegate, AdMobInterstitialDelegate, GADInterstitialDelegate {

let scene = GameScene()

var interstitial: GADInterstitial!

@IBOutlet weak var adbanner: GADBannerView!

override func viewDidLoad() {

    interstitial = GADInterstitial(adUnitID: "ca-app-pub-1279952988973855/9087084328")
    let request = GADRequest()
    // Request test ads on devices you specify. Your test device ID is printed to the console when
    // an ad request is made.
    request.testDevices = [ kGADSimulatorID, "2077ef9a63d2b398840261c8221a0c9b" ]
    interstitial.load(request)

    //self.createInterstitialAd()


    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

    }
}

func createInterstitialAd(){
    if interstitial.isReady {
        interstitial.present(fromRootViewController: self)
    } else {
        print("Ad wasn't ready")
    }
}

我的GameScene中有以下代码:

import SpriteKit
import GameplayKit
import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {

    var adDelegate: AdMobInterstitialDelegate?

    func createGameOver(){ 
    self.adDelegate?.createInterstitialAd()
}

我不知道到底出了什么问题,我感觉我在协议中错误地设置了createInterstitialAd()函数,但我真的不确定。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您正在创建的场景是SKScene,而不是您的子类GameScene。

更改:

if let scene = SKScene(fileNamed: "GameScene") {

要:

if let scene = GameScene(fileNamed: "GameScene") {

此外,您没有设置委托引用adDelegate,因此它保持为nil,并且由于条件解包(即?)而不会发生对createInterstitialAd的调用。

后:

scene.scaleMode = .aspectFill

添加:

scene.adDelegate = self

(另外,你不需要'self。'in:

self.adDelegate?.createInterstitialAd()

但这不会引起问题,这是没有必要的。)