Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current ViewController in external method in Swift

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 ***

    }

}

}
like image 657
Vinícius Barcelos Avatar asked Dec 24 '22 14:12

Vinícius Barcelos


1 Answers

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()

like image 141
Ayush Yadav Avatar answered Dec 28 '22 10:12

Ayush Yadav