Skip to content

Instantly share code, notes, and snippets.

@raaowx
Last active March 2, 2023 16:54
Show Gist options
  • Save raaowx/a54226b8cd4c6757a72e491c439c0d1f to your computer and use it in GitHub Desktop.
Save raaowx/a54226b8cd4c6757a72e491c439c0d1f to your computer and use it in GitHub Desktop.
Swift - UIKit - UIViewController
import UIKit
extension UIViewController {
/// Print through console the current view controllers hierarchy.
func printHierarchy() {
let log = { (str: String) in
print("*** *** *** *** *** *** *** *** ***")
print(str)
print("*** *** *** *** *** *** *** *** ***")
}
var rootVC: UIViewController?
if #available(iOS 15, *) {
rootVC = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.flatMap({ $0.windows })
.first(where: { $0.isKeyWindow })?.rootViewController
} else if #available(iOS 13, *) {
rootVC = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController
} else {
rootVC = UIApplication.shared.keyWindow?.rootViewController
}
guard let rootVC = rootVC else {
log("RootViewController not found!")
return
}
log("\(rootVC.value(forKey: "_printHierarchy") ?? "Hierarchy not found!")")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment