如何从 Google 登录中检索年龄和性别

2024-03-14

我已将 Google 登录集成到我的 iOS 应用程序中。我想访问用户的性别和年龄。该文档不够清楚,无法了解如何执行此操作。我发现我应该请求正确的范围。我没有在文档中找到正式的范围列表,并且我不知道应该使用哪个范围。我也不知道当我得到数据时应该如何检索数据。如果有人帮助我从 Google 获取此信息,我将不胜感激。谢谢!
这是我的代码:

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 :

只需使用以下方法:

 func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
                  withError error: Error!)

用户信息检索代码:并将此代码放入上面的方法中 -

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(),否则闭包将不会被调用。我花了三天时间才弄清楚这一点。所以我希望这会对某人有所帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 Google 登录中检索年龄和性别 的相关文章

随机推荐