Google Plus - 在获取朋友详细信息时出错

时间:2015-01-12 07:14:26

标签: ios objective-c google-plus

您好我已成功加入Google +。现在我试图获取朋友的详细信息,如电子邮件,图片,名称。但是收到错误。

任何人都可以帮助我,我犯了错误 -

我试过这段代码 -

- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
               error: (NSError *) error {

    self.plusService.authorizer = auth;

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

// 1.创建| GTLServicePlus |向Google +发送请求的实例。

    GTLServicePlus* plusService = [[GTLServicePlus alloc] init] ;

    plusService.retryEnabled = YES;

// 2.设置有效的| GTMOAuth2Authentication |作为作者的对象。

    [plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];

// 3.使用" v1" Google+ API的版本。*

    plusService.apiVersion = @"v1";
    GTLQueryPlus *query = [GTLQueryPlus queryForPeopleListWithUserId:@"me" collection:kGTLPlusCollectionVisible];

    [plusService executeQuery:query
            completionHandler:^(GTLServiceTicket *ticket,
                                GTLPlusPeopleFeed *person,
                                NSError *error) {
        if (error)
             {
               GTMLoggerError(@"Error: %@", error);
             }
             else {

                 NSArray *peopleList = person.items;
                 NSLog(@"--People_List--->%@",peopleList);

             }}];

  }

获取错误 -

[lvl=3] __41-[ViewController finishedWithAuth:error:]_block_invoke() Error: Error Domain=com.google.GTLJSONRPCErrorDomain Code=401 "The operation couldn’t be completed. (Invalid Credentials)" UserInfo=0x7b0a1d10 {error=Invalid Credentials, GTLStructuredError=GTLErrorObject 0x7b089360: {message:"Invalid Credentials" code:401 data:[1]}, NSLocalizedFailureReason=(Invalid Credentials)}

1 个答案:

答案 0 :(得分:0)

获取朋友详细信息,您可以使用Google通讯录API

在那个用途中

#import "GDataFeedContact.h"
#import "GDataContacts.h"

类文件

然后使用此代码获取数据

 -(void)getGoogleContacts
    {
        GDataServiceGoogleContact *service = [self contactService];
        GDataServiceTicket *ticket;

        BOOL shouldShowDeleted = TRUE;


        const int kBuncha = 2000;

        NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];

        GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
        [query setShouldShowDeleted:shouldShowDeleted];
        [query setMaxResults:kBuncha];

        ticket = [service fetchFeedWithQuery:query
                                    delegate:self
                           didFinishSelector:@selector(contactsFetchTicket:finishedWithFeed:error:)];

        [self setContactFetchTicket:ticket];
    }

    - (void)setContactFetchTicket:(GDataServiceTicket *)ticket
    {
        mContactFetchTicket = ticket;
    }

    - (GDataServiceGoogleContact *)contactService
    {
        static GDataServiceGoogleContact* service = nil;

        if (!service) {
            service = [[GDataServiceGoogleContact alloc] init];

            [service setShouldCacheResponseData:YES];
            [service setServiceShouldFollowNextLinks:YES];
        }


  //pass the useremail and password.here

        NSString *username = @"youremai@gmail";
        NSString *password = @"yourpassword";


        [service setUserCredentialsWithUsername:username
                                       password:password];

        return service;
    }


    - (void)contactsFetchTicket:(GDataServiceTicket *)ticket
               finishedWithFeed:(GDataFeedContact *)feed
                          error:(NSError *)error {

        if (error) {
            NSDictionary *userInfo = [error userInfo];
            NSLog(@"Contacts Fetch error :%@", [userInfo objectForKey:@"Error"]);
            if ([[userInfo objectForKey:@"Error"] isEqual:@"BadAuthentication"]) {

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                                    message:@"Authentication Failed"
                                                                   delegate:self
                                                          cancelButtonTitle:@"Ok"
                                                          otherButtonTitles:nil, nil];
                [alertView show];
            } else {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                                    message:@"Failed to get Contacts."
                                                                   delegate:self
                                                          cancelButtonTitle:@"Ok"
                                                          otherButtonTitles:nil, nil];
                [alertView show];
            }
        } else {

            NSArray *contacts = [feed entries];
            NSLog(@"Contacts Count: %d ", [contacts count]);
            [googleContacts removeAllObjects];
            for (int i = 0; i < [contacts count]; i++) {
                GDataEntryContact *contact = [contacts objectAtIndex:i];

                // Name
                NSString *ContactName = [[[contact name] fullName] contentStringValue];
                NSLog(@"Name    :  %@", ContactName);

                // Email
                GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
                NSString *ContactEmail =  @"";
                if (email && [email address]) {
                    ContactEmail = [email address];
                    NSLog(@"EmailID :  %@", ContactEmail);
                }

                // Phone
                GDataPhoneNumber *phone = [[contact phoneNumbers] objectAtIndex:0];
                NSString *ContactPhone = @"";
                if (phone && [phone contentStringValue]) {
                    ContactPhone = [phone contentStringValue];
                    NSLog(@"Phone   :  %@", ContactPhone);
                }

                // Address
                GDataStructuredPostalAddress *postalAddress = [[contact structuredPostalAddresses] objectAtIndex:0];
                NSString *address = @"";
                if (postalAddress) {
                    NSLog(@"formattedAddress   :  %@", [postalAddress formattedAddress]);
                    address = [postalAddress formattedAddress];
                }

                // Birthday
                NSString *dob = @"";
                if ([contact birthday]) {
                    dob = [contact birthday];
                    NSLog(@"dob   :  %@", dob);
                }

                if (!ContactName || !(ContactEmail || ContactPhone) ) {
                    NSLog(@"Empty Contact Fields. Not Adding.");
                }
                else
                {
                    if (!ContactEmail ) {
                        ContactEmail = @"";
                    }
                    if (!ContactPhone ) {
                        ContactPhone = @"";
                    }
                    NSArray *keys = [[NSArray alloc] initWithObjects:@"name", @"emailId", @"phoneNumber", @"address", @"dob", nil];
                    NSArray *objs = [[NSArray alloc] initWithObjects:ContactName, ContactEmail, ContactPhone, address, dob, nil];
                    NSDictionary *dict = [[NSDictionary alloc] initWithObjects:objs forKeys:keys];

                    [googleContacts addObject:dict];
                }
            }
            NSSortDescriptor *descriptor =
            [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
            [googleContacts sortUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];

      get the more info refer this http://dipinkrishna.com/blog/2013/07/ios-google-contacts/4/