I've integrated Google Sign-In into my iOS app. I would like to access user's gender and age. The documentation is not clear enough to see how to do this. I've figured out that I should request the right scope. I haven't found an official list of scopes in the documentation, and I don't know which scope I should use. Also I don't know how I should retrieve the data when I get it. I would appreciate if someone help me to get this info from Google. Thanks!
Here's my code:
func googleLogin() {
self.appDelegate.setIdentityAvailableValue(false)
GIDSignIn.sharedInstance().clientID = kClientId
GIDSignIn.sharedInstance().shouldFetchBasicProfile = true
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()
}
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil) {
let idToken = user.authentication.idToken
let url = NSURL(string: "https://www.googleapis.com/oauth2/v3/userinfo?access_token=\(user.authentication.accessToken)")
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
//UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
print("dataTaskWithURL error \(error)")
}
else {
do {
let userData = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject]
/*
Get the account information you want here from the dictionary
Possible values are
"id": "...",
"email": "...",
"verified_email": ...,
"name": "...",
"given_name": "...",
"family_name": "...",
"link": "https://plus.google.com/...",
"picture": "https://lh5.googleuserco...",
"gender": "...",
"locale": "..."
so in my case:
*/
let gender = userData!["gender"] as! String
let locale = userData!["locale"] as! String
print("gender = \(gender)")
print("locale = \(locale)")
} catch {
NSLog("Account Information could not be loaded")
}
}
})
} else {
// some error handling code
}
}
This is Swift 3 :
Simply use following method :
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!)
User info retrieving Code : and put this code inside above method -
let gplusapi = "https://www.googleapis.com/oauth2/v3/userinfo?access_token=\(user.authentication.accessToken!)"
let url = NSURL(string: gplusapi)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
do {
let userData = try JSONSerialization.jsonObject(with: data!, options:[]) as? [String:AnyObject]
let picture = userData!["picture"] as! String
let gender = userData!["gender"] as! String
let locale = userData!["locale"] as! String
} catch {
NSLog("Account Information could not be loaded")
}
}).resume()
You need to call resume() at the end or else the closure will not get called.It took me three days to figure this out. So I hope this will help somebody.
You can only access what a user has set to public. If the user doesn't want this information public then you cant have the information.
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
withError error: NSError!) {
if (error == nil) {
// Perform any operations on signed in user here.
let userId = user.userID // For client-side use only!
let idToken = user.authentication.idToken // Safe to send to the server
let name = user.profile.name
let email = user.profile.email
let url = NSURL(string: "https://www.googleapis.com/oauth2/v3/userinfo?access_token=\(user.authentication.accessToken)")
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url!) {(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
do {
let userData = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject]
/*
Get the account information you want here from the dictionary
Possible values are
"id": "...",
"email": "...",
"verified_email": ...,
"name": "...",
"given_name": "...",
"family_name": "...",
"link": "https://plus.google.com/...",
"picture": "https://lh5.googleuserco...",
"gender": "...",
"locale": "..."
so in my case:
*/
let gender = userData!["gender"] as! String
let locale = userData!["locale"] as! String
} catch {
NSLog("Account Information could not be loaded")
}
}
} else {
print("\(error.localizedDescription)")
}
}
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
withError error: NSError!) {
// Perform any operations when the user disconnects from app here.
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With