UIApplication+Sweeter.swift 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // UIApplication+Sweeter.swift
  3. //
  4. // Created by Yonat Sharon on 2019-02-08.
  5. //
  6. import UIKit
  7. public extension UIApplication {
  8. /// Sweeter: `keyWindow` for scene-based apps
  9. var legacyKeyWindow: UIWindow? {
  10. if #available(iOS 13, *) {
  11. return windows.first { $0.isKeyWindow }
  12. } else {
  13. return keyWindow
  14. }
  15. }
  16. /// Sweeter: Returns the currently top-most view controller.
  17. class func topViewController(base: UIViewController? = UIApplication.shared.legacyKeyWindow?.rootViewController) -> UIViewController? {
  18. if let nav = base as? UINavigationController {
  19. return topViewController(base: nav.visibleViewController)
  20. }
  21. if let tab = base as? UITabBarController {
  22. if let selected = tab.selectedViewController {
  23. return topViewController(base: selected)
  24. }
  25. }
  26. if let presented = base?.presentedViewController {
  27. return topViewController(base: presented)
  28. }
  29. return base
  30. }
  31. /// Sweeter: Show `viewController` over the top-most view controller.
  32. class func present(_ viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
  33. DispatchQueue.main.async {
  34. topViewController()?.present(viewController, animated: animated, completion: completion)
  35. }
  36. }
  37. }