在连接到GameViewController的场景中呈现插播广告?
我已将横幅视图集成到我的应用程序中的一个场景中,但我未能将Interstitial广告集成到另一个场景中。 这里是我的代码: 进口SpriteKit 进口的GameKit 进口GoogleMobileAds在连接到GameViewController的场景中呈现插播广告?
class GameOverMenu: SKScene, GKGameCenterControllerDelegate, UIAlertViewDelegate {
var viewController: GameViewController!
var interstitial: GADInterstitial!
var myTimer = Timer()
override func didMove(to view: SKView) {
createAndLoadInterstitial()
startMyTimer()
}
func createAndLoadInterstitial() {
interstitial = GADInterstitial(adUnitID: "...")
let request = GADRequest()
request.testDevices = [ kGADSimulatorID, "..." ]
interstitial.load(request)
}
func startMyTimer() {
myTimer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(GameOverMenu.myFunction), userInfo: nil, repeats: false)
}
func myFunction(){
if interstitial.isReady {
interstitial.present(fromRootViewController: viewController)
} else {
print("Ad wasn't ready")
}
}
当它试图与加载它失败“致命错误:意外发现零而展开的可选值”。问题出现在下面,就好像代码是这样显示的,我在应用程序启动时加载GameOver场景可以正常工作。我怎样才能解决这个问题?
if let view = self.view as! SKView? {
// Load the SKScene from 'MainMenu.sks'
if let scene = MainMenuScene(fileNamed: "MainMenu") {
scene.viewController = self
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
if let scene3 = GameOverMenu(fileNamed: "GameOver") {
scene3.viewController = self
// Set the scale mode to scale to fit the window
scene3.scaleMode = .aspectFill
view.presentScene(scene3)
}
的问题是,当你2个场景之间转换,你将失去参考GameViewController e.g
scene3.viewController = self
这就是当你启动应用程序,为什么它才会起作用。
您还在用!对这些属性
var viewController: GameViewController!
var interstitial: GADInterstitial!
所以如果他们是零你会崩溃。所以你应该一直使用?当你不是100%肯定有什么东西时。
var viewController: GameViewController?
var interstitial: GADInterstitial?
而且比你的代码如“myFunction”你会使用“?”和“如果让”在属性为零时不会崩溃。
if let ad = interstitial, let vc = viewController, ad.isReady {
ad.present(fromRootViewController: vc)
} else {
print("Ad wasn't ready")
}
有关问题的一般解决方法是,你真的应该直接将你的所有的AdMob代码到GameViewController。您可以使用类似NotificationCenter或委托的方式将来自场景的消息转发给ViewController以显示广告。在你的SKScenes中引用你的ViewController并不是最好的做法。
所以把所有的广告代码到你的ViewController,比GameViewController类实现之外创建这个扩展的通知关键
extension Notification.Name {
static let showAd = Notification.Name(rawValue: "NotificationShowAd")
}
class GameViewController: UIViewController {...
比GameViewController在viewDidLoad中可以添加观察者
override func viewDidLoad() {
super.viewDidLoad()
createAndLoadInterstitial()
NotificationCenter.default.addObserver(self, selector: #selector(myFunction), name: .showAd, object: nil)
....
}
现在,无论何时您需要展示来自任何SKScenes的广告,您都可以拨打此电话
NotificationCenter.default.post(name: .showAd, object: nil)
为了使您的生活更轻松看看我的助手在GitHub上
https://github.com/crashoverride777/SwiftyAds
希望这有助于