Search code examples
iosswiftsprite-kitappdelegateskscene

How to use applicationWillTerminate for a specific SKScene?


I have an SKScene that displays the players that joined the current room. If any of those players leaves the room (by clicking on the Leave button) their players list will be updated.

But if I close the app from one of the players, that specific player remains in the room. I want to call my leaveRoom function from the applicationWillTerminate so all the data will work fine. Is it possible? How can I resolve this issue?


Solution

  • You can make an observer to intercept it:

    override func didMove(to view: SKView) {        
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(GameScene.applicationWillTerminate(notification:)),
                name: NSNotification.Name.UIApplicationWillTerminate,
                object: nil)
    }
    func applicationWillTerminate(notification: NSNotification) {
       // put your code here
    }
    

    You can remove the observer to :

    override func willMove(from view: SKView) {
        NotificationCenter.default.removeObserver(self)
    }