4

I'm making a external function to check if user is already logged into Firebase.

My code is working, but in trying to ensure that current VC is dismissing in the end, I get an error.

My question is: How can i get the current VC or how can i use self. to reference the current VC that function is called?

class Helper{

static func checkIfLogged()  {

    Auth.auth().addStateDidChangeListener { auth, user in

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "HomeViewController")
        UIApplication.shared.keyWindow?.rootViewController = controller

        self.dismiss(animated: true, completion: nil) **** ERROR IS HERE ***

    }

}

}
  • You want to avoid passing the current view controller to the `checkIfLogged()` method? In that case see: https://stackoverflow.com/questions/9009646/current-view-controller-from-appdelegate – Xvolks Aug 19 '17 at 15:28
  • I want to pass, but how can i instantiate the current view controller in this function? – Vinícius Barcelos Aug 19 '17 at 15:30
  • 1
    What about : `static func checkIfLogged(vc: UIViewController) {`? Then `vc.dismiss(`... – Xvolks Aug 19 '17 at 15:32
  • Great. That was exactly was i looking for. Than is just i call Helper.checkIfLogged(vc: self), right? – Vinícius Barcelos Aug 19 '17 at 15:38
  • If the caller is always the current view controller, yes. You should place this method inside an extension of `UIViewController` in that case. – Xvolks Aug 19 '17 at 15:39

1 Answers1

11
extension UIApplication{
class func getPresentedViewController() -> UIViewController? {
    var presentViewController = UIApplication.shared.keyWindow?.rootViewController
    while let pVC = presentViewController?.presentedViewController
    {
        presentViewController = pVC
    }

    return presentViewController
  }
}

just add this extension and call : UIApplication. getPresentedViewController()

Ayush Yadav
  • 294
  • 5
  • 11