Call function on app termination in Swift

落爺英雄遲暮 提交于 2019-12-08 03:59:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!