Swift
简短回答
使用NotificationCenter
观察者而不是viewWillAppear
。
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func willEnterForeground() {
}
长回答
要找出应用程序何时从后台返回,请使用 NotificationCenter
观察者,而不是 viewWillAppear
。这是一个演示事件发生时间的示例项目。(这是此 Objective-C 回答的改编版本。)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
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")
}
@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:
来确定你的应用程序何时重新进入活动状态。 - sudo rm -rfisMemberOfClass
或isKindOfClass
。 - sudo rm -rf