How to retrieve age and gender from Google Sign-In

Viewed 6541

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
    }
}
2 Answers
Related