Using Google+ iOS API how to get logged in user's profile details?

限于喜欢 提交于 2019-12-31 08:41:30

问题


I've managed to successfully log in to google plus from an iPhone app. But how to get logged in user's details? such as profile id, email etc.

I tried this, Stackoverflow answer for a similar question but I was unable to get it working. In that sample what exactly is being passed to accessTocken here,

NSString *str =  [NSString stringWithFormat:@"https://www.googleapis.com/oauth2/v1/userinfo?access_token=%@",accessTocken];

I've implemented that code in - (void)finishedWithAuth: (GTMOAuth2Authentication *)auth error: (NSError *) error { } method. however auth.accessToken returns a null value.

so I can not use auth.accessToken to append that URL. Is there any other way to get this done?


回答1:


- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error {
    NSLog(@"Received Error %@ and auth object==%@", error, auth);

    if (error) {
        // Do some error handling here.
    } else {
        [self refreshInterfaceBasedOnSignIn];

        GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:@"me"];

        NSLog(@"email %@ ", [NSString stringWithFormat:@"Email: %@",[GPPSignIn sharedInstance].authentication.userEmail]);
        NSLog(@"Received error %@ and auth object %@",error, auth);

        // 1. Create a |GTLServicePlus| instance to send a request to Google+.
        GTLServicePlus* plusService = [[GTLServicePlus alloc] init] ;
        plusService.retryEnabled = YES;

        // 2. Set a valid |GTMOAuth2Authentication| object as the authorizer.
        [plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];

        // 3. Use the "v1" version of the Google+ API.*
        plusService.apiVersion = @"v1";
        [plusService executeQuery:query
                completionHandler:^(GTLServiceTicket *ticket,
                                    GTLPlusPerson *person,
                                    NSError *error) {
            if (error) {
                //Handle Error
            } else {
                NSLog(@"Email= %@", [GPPSignIn sharedInstance].authentication.userEmail);
                NSLog(@"GoogleID=%@", person.identifier);
                NSLog(@"User Name=%@", [person.name.givenName stringByAppendingFormat:@" %@", person.name.familyName]);
                NSLog(@"Gender=%@", person.gender);
            }
        }];
    }
}

Hope, this will help you




回答2:


This is the easiest and the simplest way of fetching the current logged in user's email id first create an instance variable of GPPSignIn class

GPPSignIn *signIn;

then initialize it in the viewDidLoad

- (void)viewDidLoad
 {
 [super viewDidLoad];

  static NSString * const kClientID = @"your client id";
  signIn = [GPPSignIn sharedInstance];
  signIn.clientID= kClientID;
  signIn.scopes= [NSArray arrayWithObjects:kGTLAuthScopePlusLogin, nil];
  signIn.shouldFetchGoogleUserID=YES;
  signIn.shouldFetchGoogleUserEmail=YES;
  signIn.delegate=self;

 }

next implement the GPPSignInDelegate in your view controller here you can get the logged in user's email id

 - (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
           error:(NSError *)error
 {  
  NSLog(@"Received Access Token:%@",auth);
  NSLog(@"user google user id  %@",signIn.userEmail); //logged in user's email id
 }



回答3:


First, follow this instructions to setup your project in Google API Console (and to download configuration file GoogleService-Info.plist) and to integrate the latest GoogleSignIn SDK
into your project: Integration Guide

A piece of code.

Here is the code for getting user info with the latest version of GoogleSignIn SDK at this moment.

#import <GoogleSignIn/GoogleSignIn.h>
//...

@interface ViewController() <GIDSignInDelegate, GIDSignInUIDelegate>
//...

- (IBAction)googleSignInTapped:(id)sender {
    [GIDSignIn sharedInstance].clientID = kClientId;// Replace with the value of CLIENT_ID key in GoogleService-Info.plist
    [GIDSignIn sharedInstance].delegate = self;
    [GIDSignIn sharedInstance].shouldFetchBasicProfile = YES; //Setting the flag will add "email" and "profile" to scopes. 

    NSArray *additionalScopes = @[@"https://www.googleapis.com/auth/contacts.readonly",
                                  @"https://www.googleapis.com/auth/plus.login",
                                  @"https://www.googleapis.com/auth/plus.me"];

    [GIDSignIn sharedInstance].scopes = [[GIDSignIn sharedInstance].scopes arrayByAddingObjectsFromArray:additionalScopes];

    [[GIDSignIn sharedInstance] signIn];
}

#pragma mark - GoogleSignIn delegates
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
    if (error) {
        //TODO: handle error
    } else {
        NSString *userId   = user.userID;
        NSString *fullName = user.profile.name;
        NSString *email    = user.profile.email;
        NSURL *imageURL    = [user.profile imageURLWithDimension:1024];
        NSString *accessToken = user.authentication.accessToken; //Use this access token in Google+ API calls.

        //TODO: do your stuff 
    }
}

- (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error {
    // Perform any operations when the user disconnects from app here.
}

- (void)signIn:(GIDSignIn *)signIn presentViewController:(UIViewController *)viewController {
    [self presentViewController:viewController animated:YES completion:nil];
}

// Dismiss the "Sign in with Google" view
- (void)signIn:(GIDSignIn *)signIn dismissViewController:(UIViewController *)viewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

Your AppDelegate.m

#import <GoogleSignIn/GoogleSignIn.h>
//...
@implementation AppDelegate

//...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //...
    return YES;
}

//For iOS 9.0 and later
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    //...
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                      annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}

//For your app to run on iOS 8 and older, 
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(nonnull id)annotation {
    //...
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:sourceApplication
                                      annotation:annotation];
}

@end

Also make sure that you've added URL Scheme with your REVERSED_CLIENT_ID which you can find in GoogleService-Info.plist.


To be able to get list of your connections in Google+ you need to enable Google People API and Google+ API for your project in Google API Console.

Then just send HTTP request to the following url: https://www.googleapis.com/plus/v1/people/me/people/visible?access_token=YOUR_ACCESS_TOKEN


To check if user has a Google+ profile just send HTTP request to the following url: https://www.googleapis.com/plus/v1/people/USER_ID?access_token=YOUR_ACCESS_TOKEN and check the value of "isPlusUser" which will be "true" or "false"

Little bonus
EXAMPLE PROJECT



来源:https://stackoverflow.com/questions/14456241/using-google-ios-api-how-to-get-logged-in-users-profile-details

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!