fixed bug in topViewController

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2024-01-08 17:00:57 -06:00
parent 46e2876f07
commit 22f156d461

View File

@ -10,26 +10,36 @@ import UIKit
extension UIApplication { extension UIApplication {
/// Helper method to find the top most viewcontroller in the app /// Synchronously finds the top most viewcontroller in the app
/// - Parameter controller: UIViewController to test against /// - Parameter controller: Optional UIViewController to start from. If nil, starts from the root view controller.
/// - Returns: Found top most UIViewController /// - Returns: The found top most UIViewController
public class func topViewController(controller: UIViewController? = UIApplication.shared.windows.first?.rootViewController) -> UIViewController? { public class func topViewController(controller: UIViewController? = nil) -> UIViewController? {
// Ensure we're on the main thread
if let nav = controller as? UINavigationController { guard Thread.isMainThread else {
return topViewController(controller: nav.visibleViewController) fatalError("topViewController must be called from the main thread")
} }
if let tab = controller as? UITabBarController { var rootController = controller
if let selected = tab.selectedViewController {
return topViewController(controller: selected) 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 topViewController(controller: presented)
} }
return controller return rootController
} }
} }