0

In my AppDelegate, I present a view controller (for universal links). I'm trying to check if the view controller I'm presenting is already shown, but my code isn't working.

let storyboard = UIStoryboard(name: "Main", bundle: nil)

guard let root = self.window?.rootViewController as? UITabBarController else {
    return
}

guard let vc = storyboard.instantiateViewController(withIdentifier: "MyViewController") as? MyViewController else {
    return
}

if (!vc.isTopViewController) {
    // If the view controller isn't visible...

    if #available(iOS 13.0, *) {
        vc.modalPresentationStyle = .automatic
    } else {
        vc.modalPresentationStyle = .overCurrentContext
    }

    root.present(vc, animated: true)
} else {
    // If the view controller is already visible...
    // This NEVER gets called
}

My check for isTopViewController always returns false, and I'm not sure why.

Here is the function isTopViewController...

import UIKit

extension UIViewController {

    public var isVisible: Bool {
        if isViewLoaded {
            return view.window != nil
        }
        return false
    }

    public var isTopViewController: Bool {
        if self.navigationController != nil {
            return self.navigationController?.visibleViewController === self
        } else if self.tabBarController != nil {
            return self.tabBarController?.selectedViewController == self && self.presentedViewController == nil
        } else {
            return self.presentedViewController == nil && self.isVisible
        }
    }
}

What's the correct way to check if my view controller is already visible?

user698515
  • 21
  • 2
  • 1
    `vc` is a new view controller instance you just created. It may the same class as the current top view controller, but it can't be the current top view controller. You need to check the *type* of the current top view controller and then either display your new vc or send the current vc a message to update its content – Paulw11 Apr 26 '20 at 22:58
  • Checkout https://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller/39857342 – Roi Zakai Apr 27 '20 at 09:06

0 Answers0