Phi*_*lip 3 google-login ios google-plus swift swift2
我按照https://developers.google.com/identity/sign-in/ios/sdk/上的说明将google登录集成到我的swift项目中.您可能知道登录成功时会调用以下函数.它被调用,但我无法弄清楚我如何只得到该字段的名字和姓氏user.profile.name.我只得到全名,但为了我的目的,我需要将名称分开:-(
func signIn(signIn: GIDSignIn, didSignInForUser user: GIDGoogleUser, withError error: NSError) {
// Perform any operations on signed in user here.
var userId: String = user.userID
// For client-side use only!
var idToken: String = user.authentication.idToken
// Safe to send to the server
var name: String = user.profile.name
var email: String = user.profile.email
}
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释我是如何得到这些信息的吗?
菲尔
好的...所以经过几个小时的Google参考搜索后,我发现了一些有趣的Google API和OAuth https://developers.google.com/identity/protocols/OAuth2我们可以通过查询https来获取更多信息 :/ /www.googleapis.com/oauth2/v3/userinfo?access_token=(感谢这个问题使用oauth为google,yahoo,twitter服务提供商获取emailId的终点是什么?)我发现我能得到一个如果用户已成功登录,则使用身份验证令牌提供大量信息...我不认为应该使用google +上面的解决方案,因为他们使用旧的SDK https://developers.google.com/+/mobile/ ios/upgrade-sdk(你需要使用这些GTLServicePlus)例如,使用OAuth和最新的谷歌SDK解决方案更安全(以备将来使用) - > https://developers.google.com/identity/sign-in/IOS /启动
但感谢您的回答:-)
对于任何有相同问题的人,下面的代码应该可以工作 - >
欢呼菲尔
编辑:谢谢jcaron!事实上那会更好的异步忘记这样做 - >更新解决方案
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil) {
var firstName = ""
var lastName = ""
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
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:
*/
firstName = userData!["given_name"] as! String
lastName = userData!["family_name"] as! String
print(firstName)
print(lastName)
} catch {
NSLog("Account Information could not be loaded")
}
}.resume()
}
else {
//Login Failed
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4410 次 |
| 最近记录: |