简体   繁体   English

检测哪个屏幕用户退出了应用

[英]Detecting which screen user exited app

I haven't been able to find anything on this so far, so if you could either guide or point me in the direction of where I can figure this out I would greatly appreciate it. 到目前为止,我还没有找到任何东西,因此,如果您可以指导或指出我可以解决的方向,我将不胜感激。

I was wondering if we can detect from what view controller a user either quit, or exited the app (through the home button or maybe even a phone call came in etc...). 我想知道我们是否可以从哪个视图控制器中检测到用户已退出或退出了应用程序(通过“主页”按钮,甚至可能打来的电话等)。 I am working on a game where users ask one another multiple questions at a time and I want to make sure that if a user views the first question, answers incorrectly and quits the app before answering the second question, he/ she cannot access the first question again on app reboot. 我正在开发一个游戏,用户一次要问多个问题,我想确保如果用户查看第一个问题,回答不正确并退出应用程序,然后再回答第二个问题,他/她将无法访问第一个问题重新启动应用程序时再次提问。 I would like it to be so that the user gets 0 points in the case the app is quit while on this view controller. 我希望它可以使用户在此视图控制器上退出应用时获得0分。

It should be simple to track this yourself by sending a notification during each viewDidAppear of each of your view controllers. 通过在每个视图控制器的每个viewDidAppear期间发送通知来自己进行跟踪,应该很简单。 Have something, say, in your AppDelegate (a singleton would be better), listen and update some persistent state regarding last view controller viewed. 例如,在您的AppDelegate中(最好是单身),监听并更新有关上次查看的视图控制器的持久状态。

Add this extension: 添加此扩展名:

extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(base: selected)
            }
        }
        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        return base
    }
}

And then from you AppDelegates applicationDidEnterBackground call it: 然后从您的AppDelegates applicationDidEnterBackground调用它:

func applicationDidEnterBackground(_ application: UIApplication) {
    if let viewController = UIApplication.topViewController() {
        print(viewController)
    }
}

Will print out: 将打印出:

<TestApp.MenuController: 0x7ff2bb501940>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM