如何从Google登录中检索年龄和性别 [英] How to retrieve age and gender from Google Sign-In

查看:642
本文介绍了如何从Google登录中检索年龄和性别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将Google登录集成到我的iOS应用中。我想访问用户的性别和年龄。文档不够清晰,不知道如何做到这一点。我发现我应该要求合适的范围。我没有在文档中找到正式的范围列表,我不知道应该使用哪个范围。我也不知道如何在获取数据时检索数据。如果有人帮我从谷歌获取此信息,我将不胜感激。谢谢!

这是我的代码:

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
    }
}


推荐答案

这是 Swift 3

只需使用以下方法:

 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()

你需要在最后调用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.

这篇关于如何从Google登录中检索年龄和性别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆