1

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.)

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
steff feyens
  • 127
  • 11
  • You have to present it from the GameViewController. Use notifications to have the SKScene tell the GameViewController to start the video ad – Nik Nov 03 '16 at 18:22
  • @Nik I've tried to create functions in the GameViewController and than call the functions in the GameScene but this didn't work. It gave me the same error when it had to call the functions. – steff feyens Nov 03 '16 at 18:25
  • Use notifications to communicate between the scene and view controller. I'll make an answer as soon as I can – Nik Nov 03 '16 at 18:26
  • @Nik I'll search a tutorial about notifications and I'll let you know if it worked! Thank you very much for helping me! – steff feyens Nov 03 '16 at 18:27
  • Is it just the communicating between scene and view controller that you're having a problem with? Or is there another issue here? – Nik Nov 03 '16 at 18:28
  • 1
    Yes it is just communicating between scene and view controller, because I tried to do this code in the GameScene.swift class ad.present(fromRootViewController: self) but the problem is that GameScene isn't a ViewController so 'self' wouldn't work. – steff feyens Nov 03 '16 at 18:30
  • 1
    Possible duplicate of [Segue from GameScene to a viewController Swift 3](http://stackoverflow.com/questions/40324149/segue-from-gamescene-to-a-viewcontroller-swift-3) – Nazmul Hasan Nov 03 '16 at 18:42

1 Answers1

4

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!

Nik
  • 1,664
  • 2
  • 14
  • 27