WindowHelper.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // WindowHelper.swift
  3. // TSLiveWallpaper
  4. //
  5. // Created by 100Years on 2024/12/20.
  6. //
  7. import UIKit
  8. class WindowHelper {
  9. /// 获取当前的 keyWindow
  10. static func getKeyWindow() -> UIWindow? {
  11. // 在 iOS 13 及以上,SceneDelegate 管理窗口
  12. if #available(iOS 13.0, *) {
  13. return UIApplication.shared.connectedScenes
  14. .compactMap { $0 as? UIWindowScene }
  15. .flatMap { $0.windows }
  16. .first { $0.isKeyWindow }
  17. } else {
  18. // iOS 13 以下直接获取 keyWindow
  19. return UIApplication.shared.keyWindow
  20. }
  21. }
  22. /// 获取当前窗口,兼容 iOS 13 及以上版本
  23. static func getCurrentWindow() -> UIWindow? {
  24. if #available(iOS 13.0, *) {
  25. // iOS 13 及以上使用 `scene` 获取当前 window
  26. guard let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else {
  27. return nil
  28. }
  29. return scene.windows.first { $0.isKeyWindow }
  30. } else {
  31. // iOS 12 及以下直接从 keyWindow 获取
  32. return UIApplication.shared.keyWindow
  33. }
  34. }
  35. /// 获取当前根视图控制器
  36. static func getRootViewController() -> UIViewController? {
  37. guard let window = getCurrentWindow() else {
  38. return nil
  39. }
  40. return window.rootViewController
  41. }
  42. /// 获取当前的视图控制器
  43. static func getCurrentViewController() -> UIViewController? {
  44. var currentViewController = getRootViewController()
  45. while let presentedViewController = currentViewController?.presentedViewController {
  46. currentViewController = presentedViewController
  47. }
  48. return currentViewController
  49. }
  50. static func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
  51. if let nav = base as? UINavigationController {
  52. return topViewController(base: nav.visibleViewController)
  53. } else if let tab = base as? UITabBarController {
  54. return topViewController(base: tab.selectedViewController)
  55. } else if let presented = base?.presentedViewController {
  56. return topViewController(base: presented)
  57. }
  58. debugPrint("当前顶层 VC 是: \(base)")
  59. return base
  60. }
  61. }