如何在Sprite-Kit中的某些场景中展示广告? [英] How to present ads during certain scenes in sprite-kit?
问题描述
这是我第一次使用swift和sprite-kit开发应用程序.我想将adMob集成到其中.我一直在寻找解决问题的方法,但没有成功.
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.
我在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)
}
此设置可以完美地在所有场景中显示广告,但是我的问题是,如何使用NotificationCenter如何使其在MainMenuScene.swift
和GameOverScene.swift
上显示?这两个都是他们自己的类.
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.
推荐答案
您提到过,您可以使用通知中心.
As you mentioned you can use Notification Center.
为您的通知创建一个密钥,以避免输入错误.您可以将其放置在项目中所需的任何位置(任何类或新的.swift文件之外)
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")
}
在您的GameViewController中,将观察者添加到ViewDidLoad
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
以及在您的SKScene中,您可以在需要显示横幅时像这样发布通知.
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)
或者,我在Github上有一个帮助程序,它将使此操作变得更加轻松和简洁.
Alternatively I have a helper on Github which will make this much easier and cleaner.
https://github.com/crashoverride777/SwiftyAds
希望这会有所帮助
这篇关于如何在Sprite-Kit中的某些场景中展示广告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!