2017-07-03 29 views
1

我知道這個問題之前已被問過,但其他問題的答案都沒有爲我工作。這裏是我的代碼:其視圖不在窗口中發表

```

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登錄按鈕時會觸發這些功能。請幫助和歡呼!

回答

1

這種情況發生時,你當前視圖控制器不是窗口的一部分,你可以改變

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) 
+0

謝謝主席先生。你是搖滾明星!我試過了這段代碼的一個變種,但它沒有工作,所以我不認爲這是'UIApplication.shared.keyWindow.rootViewcontroller'是問題。再次謝謝你! –

+0

你甚至包含了導航和標籤選擇。你真的是搖滾明星! –

+0

沒問題,歡迎使用@ReyCerio。 – SuryaKantSharma

相關問題