其视图不在 windows 层次结构中

whose view is not in the windows heirarchy

我知道之前有人问过这个问题,但是 none 其他问题的答案对我有用。这是我的代码:

```

var values = [String: AnyObject]()

func loginUserToFirebase(_ completion: () -> Void) {
    let accessToken = FBSDKAccessToken.current()
    guard let accessTokenString = accessToken?.tokenString else {fatalError()}
    let credentials = FIRFacebookAuthProvider.credential(withAccessToken: accessTokenString)
    FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
        if error != nil {
            print(error ?? "Something went wrong")
            return
        }
        self.fbGraphRequest()
    })
}

internal func fbGraphRequest(){
    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, error) in
        if error != nil {
            print(error ?? "error unknown")
            return
        } else {
            print(result ?? "no result")
            self.values = result as! [String: AnyObject]
            print(self.values)
            weak var rootViewModel = RootViewModel()
            rootViewModel?.values = self.values
            self.presentRootViewController()
        }
    }
}

internal func presentRootViewController() {
    let loginController = LoginController()
    let rootViewController = RootViewController()
        loginController.present(rootViewController, animated: true, 
completion: nil)

}

```

这是我的错误: Attempt to present <Art_Cache.RootViewController: 0x7fa6a1c2aab0> on <Art_Cache.LoginController: 0x7fa6a1c840b0> whose view is not in the window hierarchy! 当我在我的 LoginViewController 中使用此代码段并使用 self.present(rootViewController, animation: true, completion: nil) 时,此代码段有效。我正在尝试将我的项目转换为 MVVM,这就是正在发生的事情。问题似乎出在 self.presentRootViewController() 附近。这些函数在按下 facebook 登录按钮时被触发。请帮助和欢呼!

当您当前的视图控制器不是 window 的一部分时会发生这种情况,您可以更改

func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController, top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }

        return base
    }


    topViewController()?.present(rootViewController, animated: true, 
    completion: nil)