steff feyens steff feyens - 1 month ago 9
Swift Question

AdMob Rewarded Video in SKScene

I'm trying to create a rewarded video ad in my sprite kit game. I want to add the rewarded video in my GameScene.swift class but the problem is that this isn't a

ViewController
but a
SKScene
.

This doesn't work because my GameScene.swift isn't a
ViewController
:

ad.present(fromRootViewController: self)


I've tried many things but nothing worked. Can someone help me please?
Thanks!

(I want to display this rewarded ad when the player dies.)

Nik Nik
Answer

In your GameViewController, setup the observer in viewWillLayoutSubviews:

override func viewWillLayoutSubviews() {

    NotificationCenter.default.addObserver(self, selector: #selector(self.startVideoAd), name: NSNotification.Name(rawValue: "showVideoRewardAd"), object: nil)

}

func startVideoAd() {

// Do something - play video ad

}

In this case, whenever this notification is called, the function inside GameViewController named startVideoAd will be run. Obviously you would want to change the name to the name of your function that you want to be run.

Then, in your GameScene, to send the notification, you would run this wherever/whenever you want to run the function inside GameViewController:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showVideoRewardAd"), object: nil)

Hope this helps!

Comments