【问题标题】:Get current ViewController in external method in Swift在 Swift 的外部方法中获取当前的 ViewController
【发布时间】:2017-08-19 15:16:43
【问题描述】:

我正在创建一个外部函数来检查用户是否已经登录到 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 ***

    }

}

}

【问题讨论】:

  • 您想避免将当前视图控制器传递给checkIfLogged() 方法吗?在这种情况下,请参阅:stackoverflow.com/questions/9009646/…
  • 我想通过,但是如何在这个函数中实例化当前的视图控制器呢?
  • 怎么样:static func checkIfLogged(vc: UIViewController) {?然后vc.dismiss(...
  • 太棒了。那正是我要找的。不仅仅是我打电话给 Helper.checkIfLogged(vc: self),对吧?
  • 如果调用者始终是当前视图控制器,是的。在这种情况下,您应该将此方法放在 UIViewController 的扩展中。

标签: ios swift firebase firebase-authentication


【解决方案1】:
extension UIApplication{
class func getPresentedViewController() -> UIViewController? {
    var presentViewController = UIApplication.shared.keyWindow?.rootViewController
    while let pVC = presentViewController?.presentedViewController
    {
        presentViewController = pVC
    }

    return presentViewController
  }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2020-06-27
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多