我正在寻找一个在应用程序退出时在UIViewController
上调用的函数。
我使用viewWillDisappear
和applicationWillTerminate
进行了尝试,但没有任何效果。
我想在此功能中保存UIViewController
的设置。
答案 0 :(得分:2)
override func viewDidLoad () {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(suspending), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(suspending), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
}
func suspending () {
print("suspending...")
}
当应用程序被换出时发生 UIApplicationWillResignActive
退出时会触发UIApplicationWillTerminate
,例如按下主页按钮时。
答案 1 :(得分:0)
您需要注册通知,以便在应用终止时知道何时进行了相应的调用。
NSNotificationCenter .defaultCenter() .addObserver(self, selector: Selector("callBack"), name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter .defaultCenter() .addObserver(self, selector: Selector("callBack"), name: UIApplicationWillTerminateNotification, object: nil)
func callback() {
// Save your settings
}
请记住删除viewWillDisappear:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter .defaultCenter() .removeObserver(self)
}
答案 2 :(得分:0)
您可以在ViewController中调用 deinit
deinit {
deleteUnsavedPhotoFromServer()
}