0

This code works fine on iOS 12 - The issue is in iOS 13+ I know it's related to the iOS 13 scenes somehow .

extension UIViewController {

    static var top: UIViewController? {
        get {
            return topViewController()
        }
    }

    static var root: UIViewController? {
        get {
            return UIApplication.shared.windows[0].rootViewController
        }
    }

    static func topViewController(from viewController: UIViewController? = UIViewController.root) -> UIViewController? {
        if let tabBarViewController = viewController as? UITabBarController {
            return topViewController(from: tabBarViewController.selectedViewController)
        } else if let navigationController = viewController as? UINavigationController {
            return topViewController(from: navigationController.visibleViewController)
        } else if let presentedViewController = viewController?.presentedViewController {
            return topViewController(from: presentedViewController)
        } else {
            return viewController
        }
    }

}

When i get the UIViewController.top using iOS 12 everything works fine, but in iOS 13 it's nil.

Any ideas how to fix this ?

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
  • You mean `return topViewController()` returns `nil`? – koen Dec 30 '19 at 17:50
  • @koen yeah its just calling .top returns that function – Mohmmad S Dec 30 '19 at 17:51
  • Can you add you view controller hierarchy to the question? Like print on console what view controllers are there in iOS 12 and what are there on iOS 13.. This will help narrow down where the problem is. – Harsh Dec 30 '19 at 17:51
  • check the value of the `root`, probably its related to `UIApplication.shared.windows[0].rootViewController` that returns `nil`. – Ahmad F Dec 30 '19 at 18:08
  • @AhmadF i did check that, but it's there it's all there at some point but then i think iOS 13 removes the uiwindow thats why – Mohmmad S Dec 30 '19 at 18:14
  • I tried your code snippet, and it works fine. `UIApplication.shared.windows[0].rootViewController` is not nil, which should get returned by default from `topViewController` method. Is `UIApplication.shared.windows[0].rootViewController` nil in your case? How many window in `UIApplication.shared.windows`? – Ahmad F Dec 30 '19 at 19:00
  • Try to replace `UIApplication.shared.windows[0].rootViewController` with `UIApplication.shared.windows.first { $0.rootViewController != nil }?.rootViewController` and check whether it works or not. – Ahmad F Dec 30 '19 at 19:22
  • @MohmmadS checkout this answer https://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller/63509132#63509132 – Muhammad Waqas Aug 27 '20 at 08:55

0 Answers0