46 lines
1.5 KiB
Swift
46 lines
1.5 KiB
Swift
//
|
|
// UIApplication.swift
|
|
// VDS
|
|
//
|
|
// Created by Matt Bruce on 4/14/23.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
|
|
extension UIApplication {
|
|
|
|
/// 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")
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
// 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 rootController
|
|
}
|
|
}
|
|
|
|
|
|
|