在Swift中的应用程序终止上调用函数

max*_*hud 1 sprite-kit swift

当我的应用程序被用户终止时,如何调用SKScene类中的函数?

当应用程序终止时,我需要修改一个值并将其保存到NSUserDefauts.

0x1*_*41E 6

您可以注册以在应用即将终止时收到通知.为此,请将观察者添加到默认通知中心

// Add this to didMoveToView in your SKScene subclass
NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
Run Code Online (Sandbox Code Playgroud)

将以下方法添加到SKScene子类中.该应用程序终止之前将调用该方法.它必须通过添加"暴露"到Objective-C,@objc因此通知程序可以使用#selector().

@objc func saveData(notification:NSNotification) {
    // Save your data here
    print("Saving data...")
}
Run Code Online (Sandbox Code Playgroud)