Pablo
Pablo

Reputation: 1332

How to reference current SKScene from the AppDelegate in Swift

I have a SKScene that has a pause method. I want to be able to do something like this:

func applicationWillTerminate(_ application: UIApplication) {
    pauseLevel()
}

However, I don't know how to get a reference to my SKScene from the AppDelegate.

I tried using

 application.inputView

However, that is an UIView. How can I get an SKScene?

EDIT

deinit {
    NotificationCenter.default.removeObserver(self)
}

override func didMove(to view: SKView) {
    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    self.backgroundColor = UIColor(red:0.17, green:0.24, blue:0.31, alpha:1.0)
    self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(runPause), name: .UIApplicationWillResignActive, object: nil)
}

would that be sufficient and effective at removing the observer every time?

Upvotes: 1

Views: 256

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

I would scrap your way of thinking. in iOS, notifications get sent for when application events happen. In your case, the notification is called UIApplicationWillTerminate

What you want to do is hook into this notification in your Scene class, I would recommend in the didMove(to:) method.

    NotificationCenter.default.addObserver(self, selector: #selector(pauseLevel), name: .UIApplicationWillTerminate, object: nil)

Now when you do this, you need to remember to remove the observer when you are removing the scene, so you want to use the code:

   NotificationCenter.default.removeObserver(self)

At moments the scene is removed. I would recommend at the least putting it in the deinit

Now in Swift 4, things change a little bit. You need to add @objc to your pauseLevel function so that it can be exposed to objective c libraries.

Upvotes: 2

Related Questions