Swift - reject the view controller from the completion block

Simple question. If I am in the completion block - for example, facebook login using firebase ... and the login succeeded. If I want to reject the current view controller (input view controller) from the completion block, I need to go back to the main queue to do this. I assume that the login completion block is executed in the background thread, and any change in the user interface (i.e., rejecting the current view controller) should be done in the main thread ... what is the best practice here ... or am I missing something

@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) } }) } }) } 
+7
source share
1 answer

You must "return" to the main thread to do this. It's pretty simple, just wrap

self.dismissViewControllerAnimated(true, completion: nil) like this ...

Swift 2.x

 dispatch_async(dispatch_get_main_queue()){ self.dismissViewControllerAnimated(true, completion: nil) } 

Swift 3 4 & 5:

 DispatchQueue.main.async { self.dismiss(animated: true, completion: nil) } 
+12
source

Source: https://habr.com/ru/post/1245439/


All Articles