From 22f156d461eaf55612aa297ad910cc1cd246e406 Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Mon, 8 Jan 2024 17:00:57 -0600 Subject: [PATCH] fixed bug in topViewController Signed-off-by: Matt Bruce --- VDS/Extensions/UIApplication.swift | 40 +++++++++++++++++++----------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/VDS/Extensions/UIApplication.swift b/VDS/Extensions/UIApplication.swift index 956bd3d5..13c41d68 100644 --- a/VDS/Extensions/UIApplication.swift +++ b/VDS/Extensions/UIApplication.swift @@ -10,26 +10,36 @@ import UIKit extension UIApplication { - /// Helper method to find the top most viewcontroller in the app - /// - Parameter controller: UIViewController to test against - /// - Returns: Found top most UIViewController - public class func topViewController(controller: UIViewController? = UIApplication.shared.windows.first?.rootViewController) -> UIViewController? { - - if let nav = controller as? UINavigationController { - return topViewController(controller: nav.visibleViewController) + /// Synchronously finds the top most viewcontroller in the app + /// - Parameter controller: Optional UIViewController to start from. If nil, starts from the root view controller. + /// - Returns: The found top most UIViewController + public class func topViewController(controller: UIViewController? = nil) -> UIViewController? { + // Ensure we're on the main thread + guard Thread.isMainThread else { + fatalError("topViewController must be called from the main thread") } - - if let tab = controller as? UITabBarController { - if let selected = tab.selectedViewController { - return topViewController(controller: selected) + + var rootController = controller + + if rootController == nil { + if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, + let rootVC = windowScene.windows.first(where: { $0.isKeyWindow })?.rootViewController { + rootController = rootVC } } - - if let presented = controller?.presentedViewController { + + // Proceed with the logic to find the top view controller + if let nav = rootController as? UINavigationController { + return topViewController(controller: nav.visibleViewController) + } else if let tab = rootController as? UITabBarController, let selected = tab.selectedViewController { + return topViewController(controller: selected) + } else if let presented = rootController?.presentedViewController { return topViewController(controller: presented) } - - return controller + + return rootController } } + +