I want to determine the current view display in SwiftUI

Hi all. When I go back from background to foreground, I want to determine which view is displayed on the screen, then handle the corresponding logic. Example: I want to define HomeView when it comes back to foreground.

You could for example have a variable which gets written to by each view controller as it loads, thus keeping a record of the last loaded view controller. Or you could recursively scan the view controllers to determine what's at the top, I did that in one of my app's, the code is below. Its specific to the structure of my app but you get the general idea.

extension UIApplication

{

    class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController?

    {

        if let nav = base as? UINavigationController

        {

            if nav.visibleViewController is UIAlertController

            {

                let top = topViewController(nav.viewControllers.last)

                return top

            }

            else

            {

                let top = topViewController(nav.visibleViewController)

                return top

            }

        }

        

        if let tab = base as? UITabBarController

        {

            if let selected = tab.selectedViewController

            {

                let top = topViewController(selected)

                return top

            }

        }

        

        if let presented = base?.presentedViewController

        {

            if presented is UIAlertController

            {

                return base

            }

            else

            {

                let top = topViewController(presented)

                return top

            }

        }

        return base

    }

}

I want to determine the current view display in SwiftUI
 
 
Q