简单的问题.如果我在一个完成块内 – 例如使用firebase登录facebook …并且登录成功.如果我想从完成块中解除当前视图控制器(登录视图控制器),我是否需要返回主队列才能执行此操作.我假设登录完成块正在后台线程上完成,并且对UI的任何更改(即解雇当前视图控制器)应该在主线程上完成…这里最好的做法是什么……或者我错过了什么?
@IBAction func facebookLoginTapped(sender: AnyObject) { // let ref = Firebase(url: "https://XXXX.firebaseio.com") let facebookLogin = FBSDKLoginManager() facebookLogin.logInWithReadPermissions(["email"],fromViewController: self,handler: { (facebookResult,facebookError) -> Void in if facebookError != nil { print("Facebook login Failed. Error \(facebookError)") } else if facebookResult.isCancelled { print("Facebook login was cancelled.") } else { //successfully logged in //get facbook access token let accessToken = FBSDKAccessToken.currentAccessToken().tokenString //use access token to authenticate with firebase ref.authWithOAuthProvider("facebook",token: accessToken,withCompletionBlock: { error,authData in if error != nil { print("Login Failed. \(error)") } else { //authData contains print("Logged in! \(authData)") //pop loginvc back to uservc - DO I NEED TO GET MAIN THREAD HERE BEFORE DISMISSING VIEW CONTROLLER self.dismissViewControllerAnimated(true,completion: nil) } }) } }) }
解决方法
你应该“弹出”回主线程来做到这一点.它非常简单,只需包裹
self.dismissViewControllerAnimated(true,completion:nil)就像这样……
Swift 2.x
dispatch_async(dispatch_get_main_queue()){ self.dismissViewControllerAnimated(true,completion: nil) }
Swift 3&斯威夫特4:
DispatchQueue.main.async { self.dismiss(animated: true,completion: nil) }