迅速
简短答案
使用NotificationCenter
观察者而不是viewWillAppear
。
override func viewDidLoad() {
super.viewDidLoad()
// set observer for UIApplication.willEnterForegroundNotification
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
// my selector that was defined above
@objc func willEnterForeground() {
// do stuff
}
长答案
要了解应用何时从后台返回,请使用NotificationCenter
观察者而不是viewWillAppear
。这是一个示例项目,显示哪些事件在何时发生。(这是对Objective-C答案的改编。)
import UIKit
class ViewController: UIViewController {
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
// add notification observers
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
print("view will appear")
}
override func viewDidAppear(_ animated: Bool) {
print("view did appear")
}
// MARK: - Notification oberserver methods
@objc func didBecomeActive() {
print("did become active")
}
@objc func willEnterForeground() {
print("will enter foreground")
}
}
首次启动应用程序时,输出顺序为:
view did load
view will appear
did become active
view did appear
按下主屏幕按钮,然后将应用返回到前台后,输出顺序为:
will enter foreground
did become active
因此,如果您最初尝试使用,viewWillAppear
那么UIApplication.willEnterForegroundNotification
可能就是您想要的。
注意
从iOS 9及更高版本开始,您无需删除观察者。该文档指出:
如果您的应用程序针对iOS 9.0和更高版本或macOS 10.11和更高版本,则无需在其dealloc
方法中注销观察者。
applicationWillEnterForeground:
用来确定应用程序何时重新进入活动状态。