Avatar ·

How to get the top-most UIViewController on the screen of an iOS app?

Hello everyone! I'm writing my first iOS app in Swift and ran into a problem. I have several modal windows (UIAlertController, UIImagePickerController, and custom view controllers) that sometimes open on top of each other. I need to programmatically get a reference to the controller that is currently at the top of the hierarchy, for example, to show a new alert or check if a modal screen is already open. I tried using `UIApplication.shared.keyWindow?.rootViewController`, but this only gives the root controller, not the currently visible one. If I open a modal controller, the rootViewController does not change. I tried recursively traversing through `presentedViewController`, but this doesn't always work, especially if there is a UINavigationController or UITabBarController.