-->

Call GameScene method from AppDelegate (Swift 3, S

2019-07-24 17:16发布

问题:

I am using Spritekit and swift 3 for create a game, my problem is when I try to call my pauseGame() method, present in my GameScene class (subclass of SKScene), from AppDelegate file within applicationWillResignActive(_ application: UIApplication) method.

I already try to instantiate GameScene class and then call the method in my AppDelegate file in this way, although there is no compiler error it doesn't work:

func applicationWillResignActive(_ application: UIApplication) {

    if let gameScene = GameScene(fileNamed: "GameScene") {

        gameScene.pauseGame()
    }
}

How can I resolve this? Thanks in advance.

回答1:

You are creating a new instance of your GameScene. To pause the existing instance you need to add a reference to it in the AppDelegate.

The better solution it to register the GameScene class to receive notifications when the app goes into the background. This is a good alternative to coupling these classes with the AppDelegate.

In your GameScene class add this in the viewDidLoad() function:

let app = UIApplication.shared

//Register for the applicationWillResignActive anywhere in your app.
NotificationCenter.default.addObserver(self, selector: #selector(GameScene.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: app)

Add this function to the GameScene class to react to the received notification:

func applicationWillResignActive(notification: NSNotification) {
     pauseGame()
}