问题
How can I call a function that is within an SKScene class when my app is terminated by the user?
I need to modify a value and save it to NSUserDefauts when the app is terminated.
回答1:
You can register to receive a notification when your app is about to terminate. To do this, add an observer to the default notification center by
// Add this to didMoveToView in your SKScene subclass
NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
Add the following method to your SKScene
subclass. The method will be called before the app terminates. It must be "exposed" to Objective-C by adding @objc
so the notifier can use #selector()
.
@objc func saveData(notification:NSNotification) {
// Save your data here
print("Saving data...")
}
回答2:
In Swift 3 and 4 you have something like that: in your viewDidLoad
NotificationCenter.default.addObserver(self, selector: #selector(toDoSomething), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
and than you have that method to be called
func suspending () {
print("toDoSomething...")
}
回答3:
There are a few methods in UIAppDelegate that will help you. Take a look at applicationWillTerminate(_:)
and applicationWillResignActive(_:)
. From there you see what state your app is in and do perform the appropriate actions.
来源:https://stackoverflow.com/questions/27010431/call-function-on-app-termination-in-swift