我按照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
}
有人可以向我解释我是如何得到这些信息的吗?
菲尔
答案 0 :(得分:7)
好的...所以经过几个小时的Google参考搜索后,我发现了一些有趣的Google API和OAuth https://developers.google.com/identity/protocols/OAuth2我们可以通过查询https://www.googleapis.com/oauth2/v3/userinfo?access_token=获取更多信息(感谢这个问题) What are the end points to get the emailId using oauth for the google, yahoo, twitter service providers?)我发现,如果用户已成功登录,我可以通过身份验证令牌获取大量信息...我不认为应该使用google +上面的解决方案,因为他们使用旧的SDK https://developers.google.com/+/mobile/ios/upgrading-sdk(您需要使用这些内容,例如GTLServicePlus
)
使用OAuth和最新的谷歌SDK解决方案更加安全(为了将来的目的) - > https://developers.google.com/identity/sign-in/ios/start
但感谢您的回答: - )
对于任何有相同问题的人,以下代码应该有效 - >
欢呼声 菲尔
编辑:谢谢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
}
}
答案 1 :(得分:1)
这与我们在制作中的内容类似:
private func finishAuthorizationForUser(signInUser: GIDGoogleUser) {
let servicePlus = GTLServicePlus()
servicePlus.authorizer = signInUser.authentication.fetcherAuthorizer()
servicePlus.fetchObjectWithURL(NSURL(string: "https://www.googleapis.com/plus/v1/people/me")!, completionHandler: { (ticket, object, error) -> Void in
guard error == nil else {
self.showUnsuccessfulLoginAlertWithMessage(error.description)
return
}
guard let user = object as? GTLObject else {
self.showUnsuccessfulLoginAlertWithMessage("Bad user")
return
}
let userJson = NSDictionary(dictionary: user.JSON) as! [String: AnyObject]
if let names = userJson["name"] as? [String: String] {
let lastName = names["familyName"]
let firstName = names["givenName"]
//...do something with these names
}
})
}
答案 2 :(得分:0)
你知道最后一个字符串每次都是姓氏:)直到数组中的姓氏作为名字或名字。将最后一个字符串视为姓氏。最后你将得到一个包含两个字符串的数组。
答案 3 :(得分:0)
您必须向Google+提出其他问题才能获取用户的详细信息。这需要将GooglePlus和GoogleOpenSource框架链接在其中。
这是Objective-C代码,对Swift的翻译留给了读者:
#import <Google/SignIn.h>
#import <GooglePlus/GooglePlus.h>
#import <GoogleOpenSource/GoogleOpenSource.h>
...
- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error
{
if (error)
{
NSLog(@"Google sign-in error: %@", error);
// do any cleanup like re-enabling buttons here
return;
}
if (!user)
{
NSLog(@"Google sign-in returned nil user");
// do any cleanup like re-enabling buttons here
return;
}
NSLog(@"Google sign-in successfull: %@, userId: %@ token: %@ name: %@ email: %@",
user,
user.userID,
user.authentication.idToken,
user.profile.name,
user.profile.email);
NSString *userId = user.userID; // For client-side use only!
NSString *idToken = user.authentication.idToken; // Safe to send to the server
NSString *name = user.profile.name;
NSString *email = user.profile.email;
__block NSString *firstName = @"";
__block NSString *lastName = @"";
__block NSString *title = @"";
NSArray *nameComponents = [name componentsSeparatedByString:@" "];
if (nameComponents.count == 2)
{
firstName = nameComponents[0];
lastName = nameComponents[1];
}
GTMOAuth2Authentication *auth = [[GTMOAuth2Authentication alloc] init];
[auth setClientID:signIn.clientID];
[auth setUserEmail:user.profile.email];
[auth setUserID:user.userID];
[auth setAccessToken:user.authentication.accessToken];
[auth setRefreshToken:user.authentication.refreshToken];
[auth setExpirationDate: user.authentication.accessTokenExpirationDate];
GTLServicePlus* plusService = [[GTLServicePlus alloc] init];
plusService.retryEnabled = YES;
plusService.authorizer = auth;
GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:@"me"];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPerson *person,
NSError *error)
{
if (error)
{
GTMLoggerError(@"Error: %@", error);
}
else
{
NSLog(@"me: %@, display name: %@, about me: %@, name: %@ / %@ gender: %@",
person, person.displayName, person.aboutMe, person.name.givenName, person.name.familyName, person.gender);
firstName = person.name.givenName;
lastName = person.name.familyName;
}
// do whatever you need with the data here
}];
}