Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Created September 21, 2023 13:46
Show Gist options
  • Save erdemildiz/7a87071b27edf2ad203cddab638ec48a to your computer and use it in GitHub Desktop.
Save erdemildiz/7a87071b27edf2ad203cddab638ec48a to your computer and use it in GitHub Desktop.
Root view controller in Swift

IOS 15

extension UIApplication {
    var firstKeyWindow: UIWindow? {
        return UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .filter { $0.activationState == .foregroundActive }
            .first?.keyWindow

    }
}

IOS 13

extension UIApplication {
    var firstKeyWindow: UIWindow? {
        return UIApplication.shared.connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .filter { $0.activationState == .foregroundActive }
            .first?.windows

            .first(where: \.isKeyWindow)

    }
}

Before iOS 13

UIApplication.shared.keyWindow?.rootViewController
// Or
UIApplication.shared.windows.first?.rootViewController

Source and details

https://sarunw.com/posts/how-to-get-root-view-controller/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment