UIApplication+Extension.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. }