How to present ads during certain scenes in sprite-kit?

主宰稳场 提交于 2019-12-11 04:55:34

问题


This is my first time developing an app using swift and sprite-kit. I would like to integrate adMob into it. I have been searching a solution to my problem but I've had no success.

I have the following code set up inside GameViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()

    bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
    bannerView.isHidden = true
    bannerView.adUnitID = "ca-app-pub-************************"
    bannerView.rootViewController = self
    view.addSubview(bannerView)

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

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

    // Create and configure the scene.
    let aspectRatio = skView.bounds.size.height / skView.bounds.size.width
    let scene = MainMenuScene(size:CGSize(width: 320, height: 320 * aspectRatio))
    skView.presentScene(scene)

    showBanner()

}

func showBanner() {
    bannerView.isHidden = false
    let request = GADRequest()
    request.testDevices = ["******************"]
    bannerView.load(request)

}

This setup displays the ad on all of my scenes perfectly but my question is, how would I be able to make it show on MainMenuScene.swift and GameOverScene.swift by using NotificationCenter? Both of these are their own class.


回答1:


As you mentioned you can use Notification Center.

Create a key for your notification to avoid typos. You can put this anywhere you like in your project (outside any class or a new .swift file)

 extension Notification.Name {
    static let showBannerAd = Notification.Name(rawValue: "ShowBanner")
 }

Than in your GameViewController add the observer in ViewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(showBanner), name: .showBannerAd, object: nil) // selector is the method to call

and in your SKScene(s) you can post the notification like so when you need to show the banner.

 NotificationCenter.default.postNotificationName(.showBannerAd, object: nil)

Alternatively I have a helper on Github which will make this much easier and cleaner.

https://github.com/crashoverride777/SwiftyAds

Hope this helps



来源:https://stackoverflow.com/questions/42593677/how-to-present-ads-during-certain-scenes-in-sprite-kit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!