I'm using the google api for ios for signing in to the mobile app (taken from here: https://developers.google.com/identity/sign-in/ios/backend-auth They are showing there how to use objective-c to make a post request to the backend server and as a result - get the info if the token is valid or not.
I established my backend server properly and it verifies if the token is good or not (and it returns the status 200
or 401
. Now I just need to send the token from the app to my server and based on its result validate the user or not.
I found this answer about making post requests: https://stackoverflow.com/a/26365148/4662074
and following this example I coded it as follows:
// [START signin_handler]
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
withError error: NSError!) {
if (error == nil) {
print("!!!! TOKEN !!!! "+user.authentication.idToken)
let request = NSMutableURLRequest(URL: NSURL(string: "http://mywebserver.com:3000/auth/token")!)
request.HTTPMethod = "POST"
let postString = "id_token="+user.authentication.idToken
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
print("Signed in as a user: "+user.profile.name)
}
task.resume()
let sb = UIStoryboard(name: "Main", bundle: nil)
if let tabBarVC = sb.instantiateViewControllerWithIdentifier("TabController") as? TabController {
self.window!.rootViewController = tabBarVC
}
} else {
print("\(error.localizedDescription)")
}
}
// [END signin_handler]
Ok, in this case right after making a call to the webservice I'm switching the view to the main page of the app:
let sb = UIStoryboard(name: "Main", bundle: nil)
if let tabBarVC = sb.instantiateViewControllerWithIdentifier("TabController") as? TabController {
self.window!.rootViewController = tabBarVC
}
But since I'm doing it right after task.resume()
- that means I'm never waiting for the result from the webservice and even if it states 401
- user is still signed it. I tried to put that piece of code above the task.resume()
but then I'm getting error:
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
So how can I include the answer from my webservice during the logging in process and if the status is 200
- then switch the view to my TabController
? (and in other cases for example ask the user to log in again)