UIApplication+Extension.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // UIApplication+Extension.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by mac on 2024/4/10.
  6. //
  7. import Foundation
  8. import UIKit
  9. public extension UIApplication {
  10. //MARK: 1.1、获取当前的keyWindow
  11. /// 获取当前的keyWindow
  12. static var keyWindow: UIWindow? {
  13. if #available(iOS 13, *) {
  14. return UIApplication.shared.windows.filter { $0.isKeyWindow }.first
  15. } else {
  16. return UIApplication.keyWindow
  17. }
  18. }
  19. // MARK: 1.2、获取根控制器
  20. /// 获取根控制器
  21. /// - Parameter base: 哪个控制器为基准
  22. /// - Returns: 返回 UIViewController
  23. static func topViewController(_ base: UIViewController? = UIApplication.keyWindow?.rootViewController) -> UIViewController? {
  24. if let nav = base as? UINavigationController {
  25. return topViewController(nav.visibleViewController)
  26. }
  27. if let tab = base as? UITabBarController {
  28. if let selected = tab.selectedViewController {
  29. return topViewController(selected)
  30. }
  31. }
  32. if let presented = base?.presentedViewController {
  33. return topViewController(presented)
  34. }
  35. return base
  36. }
  37. // MARK: 1.3、网络状态是否可用
  38. /// 网络状态是否可用
  39. static func reachable() -> Bool {
  40. let data = NSData(contentsOf: URL(string: "https://www.baidu.com/")!)
  41. return (data != nil)
  42. }
  43. }
  44. import UIKit
  45. extension UIApplication {
  46. @MainActor
  47. static func currentViewController() -> UIViewController? {
  48. var rootViewController: UIViewController?
  49. // iOS 13+ 使用 WindowScene
  50. if #available(iOS 13.0, *) {
  51. rootViewController = UIApplication.shared.connectedScenes
  52. .compactMap { $0 as? UIWindowScene }
  53. .first?
  54. .windows
  55. .first(where: { $0.isKeyWindow })?
  56. .rootViewController
  57. }
  58. // iOS 12 及以下使用 keyWindow
  59. else {
  60. rootViewController = UIApplication.keyWindow?.rootViewController
  61. }
  62. return rootViewController?.findCurrentViewController()
  63. }
  64. }
  65. extension UIViewController {
  66. @MainActor
  67. func findCurrentViewController() -> UIViewController {
  68. if let nav = self as? UINavigationController {
  69. return nav.visibleViewController?.findCurrentViewController() ?? nav
  70. }
  71. if let tab = self as? UITabBarController {
  72. return tab.selectedViewController?.findCurrentViewController() ?? tab
  73. }
  74. if let presented = self.presentedViewController {
  75. return presented.findCurrentViewController()
  76. }
  77. return self
  78. }
  79. }