在Swift中的外部方法中获取当前的ViewController

Vin*_*los 1 ios firebase swift firebase-authentication

我正在做一个外部功能来检查用户是否已经登录到Firebase。

我的代码正在运行,但是在尝试确保最终关闭当前的VC时,出现错误。

我的问题是:如何获得当前的VC或如何使用self。引用该函数被调用的当前VC?

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

    }

}

}
Run Code Online (Sandbox Code Playgroud)

Ayu*_*dav 6

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

    return presentViewController
  }
}
Run Code Online (Sandbox Code Playgroud)

只需添加此扩展名并调用:UIApplication。getPresentedViewController()