Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function on app termination in Swift

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.

like image 912
Max Hudson Avatar asked Mar 02 '26 19:03

Max Hudson


1 Answers

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

Swift 5:

 NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: UIApplication.willTerminateNotification, object: nil)

Swift 3/4:

// 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...")
}
like image 128
0x141E Avatar answered Mar 05 '26 08:03

0x141E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!