Подтвердить что ты не робот

Используя API Google+ iOS, как войти в профиль пользователя?

Мне удалось успешно войти в Google plus из приложения iPhone. Но как войти в детали пользователя? таких как идентификатор профиля, электронная почта и т.д.

Я попробовал это, qaru.site/info/538994/..., но я не смог заставить его работать. В этом примере, что именно передается в accessTocken здесь,

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

Я реализовал этот код в методе - (void)finishedWithAuth: (GTMOAuth2Authentication *)auth error: (NSError *) error { }. однако auth.accessToken возвращает нулевое значение.

поэтому я не могу использовать auth.accessToken для добавления этого URL-адреса. Есть ли другой способ сделать это?

4b9b3361

Ответ 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);
            }
        }];
    }
}

Надеюсь, это поможет вам

Ответ 2

Это самый простой и простой способ получения текущего зарегистрированного идентификатора электронной почты пользователя сначала создайте переменную экземпляра класса GPPSignIn

GPPSignIn *signIn;

затем инициализируйте его в 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;

 }

затем выполните GPPSignInDelegate в вашем контроллере вида  здесь вы можете получить зарегистрированный идентификатор электронной почты пользователя

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

Ответ 3

Сначала следуйте этим инструкциям для настройки вашего проекта в Google API Console (и загрузить файл конфигурации GoogleService-Info.plist) и интегрировать последние GoogleSignIn SDK
в ваш проект: Руководство по интеграции

Кусок кода.

Вот код для получения информации о пользователе с последней версией GoogleSignIn SDK в данный момент.

#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];
}

Ваш 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

Также убедитесь, что вы добавили схему URL с REVERSED_CLIENT_ID, которую вы можете найти в GoogleService-Info.plist.


Чтобы иметь возможность получать список ваших подключений в Google+, вам необходимо включить Google People API и Google+ API для вашего проекта в Консоль API Google.

Затем просто отправьте HTTP-запрос на следующий URL-адрес: https://www.googleapis.com/plus/v1/people/me/people/visible?access_token=YOUR_ACCESS_TOKEN


Чтобы проверить, имеет ли пользователь профиль Google+, просто отправьте HTTP-запрос на следующий URL-адрес: https://www.googleapis.com/plus/v1/people/USER_ID?access_token=YOUR_ACCESS_TOKEN и проверьте значение "isPlusUser", которое будет "true" или "false"

введите описание изображения здесь

Маленький бонус
ПРИМЕР ПРОЕКТА