swift - swift - 如何检测从哪个 ViewController 应用程序进入后台?
问题描述
在我的 swift 应用程序中,我需要知道我的应用程序从哪个屏幕进入后台。我试图用NotificationCenter
这种方式:
class MainViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundMain), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
@objc func appMovedToBackgroundMain() {
print("main - App moved to Background!")
}
}
class InitViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundInit), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
@objc func appMovedToBackgroundInit() {
print("init - App moved to Background!")
}
}
当我在 Xcode 的控制台中按下Home
按钮时,这些行:MainViewController
init - App moved to Background!
main - App moved to Background!
我预计那里只有一条线 - main - App moved to Background!
。我怎样才能做到这一点?
解决方案
在 AppDelegate Methods:applicationDidEnterBackground
或applicationWillEnterForeground
上,您可以获得最顶层的 UIViewController。在这个问题上有很好的解释:Get top most UIViewController
推荐阅读
- oracle - 在预期的地方找不到 FROM 关键字 - 基本查询
- node.js - 调用 CMD 时 exec() 无法正确编码某些字符
- html - jQuery没有在提交时执行
- android - 使用 Android 游戏服务、Apple Game Center 和 Facebook 在 Unity3D 中制作游戏时是否需要单独的数据库
- c++ - MKTIME 总是返回 -1 (Window10_64bit / MSVS2019 / C++)
- c - rpcgen only one argument is allowed 错误
- ruby - 生成一系列最大和为 100 的非随机数
- php - 使用 laravel 框架在服务器上上传大文件?
- javascript - Gulp - 带循环的异步完成
- ssh - 将托管堆栈服务器连接到 AzureAD