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 {
/// 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
}
}