iPhone(iOS) programming: Get Google Contacts

4. Retrieve Contacts.

Lets add code to retrieve the contacts.

ViewController.h

//
//  ViewController.h
//  GoogleContacts
//
//  Created by Dipin Krishna on 20/02/13.
//  Copyright (c) 2013 Dipin Krishna. All rights reserved.
//
 
#import <UIKit/UIKit.h>
#import "GDataFeedContact.h"
#import "GDataContacts.h"
 
@interface ViewController : UIViewController {
    NSMutableArray *googleContacts;
 
    GDataServiceTicket *mContactFetchTicket;
    NSError *mContactFetchError;
}
@property (weak, nonatomic) IBOutlet UITextField *usernameTxt;
@property (weak, nonatomic) IBOutlet UITextField *passwordTxt;
 
- (IBAction)getContacts:(id)sender;
@end

ViewController.m

//
//  ViewController.m
//  GoogleContacts
//
//  Created by Dipin Krishna on 20/02/13.
//  Copyright (c) 2013 Dipin Krishna. All rights reserved.
//
 
#import "ViewController.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    googleContacts = [[NSMutableArray alloc] init];
}
 
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
- (IBAction)getContacts:(id)sender {
    if ([[self.usernameTxt text] isEqual:@""] || [[self.passwordTxt text] isEqual:@""]) {
        NSLog(@"Username and Password is Required.");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                            message:@"Username and Password is Required."
                                                           delegate:self
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil, nil];
        [alertView show];
    } else {
        NSLog(@"Get Google Contacts");
        [self getGoogleContacts];
    }
}
 
-(void)getGoogleContacts
{
    GDataServiceGoogleContact *service = [self contactService];
    GDataServiceTicket *ticket;
 
    BOOL shouldShowDeleted = TRUE;
 
    // request a whole buncha contacts; our service object is set to
    // follow next links as well in case there are more than 2000
    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];
    }
 
    // update the username/password each time the service is requested
    NSString *username = [self.usernameTxt text];
    NSString *password = [self.passwordTxt text];
 
    [service setUserCredentialsWithUsername:username
                                   password:password];
 
    return service;
}
 
// contacts fetched callback
- (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 && [postalAddress formattedAddress]) {
                NSLog(@"Formatted Address   :  %@", [postalAddress formattedAddress]);
                address = [postalAddress formattedAddress];
            }
 
            // Birthday
            NSString *dob = @"";
            if ([contact birthday]) {
		dob = [contact birthday];
                NSLog(@"dob   :  %@", dob);
            }
 
	    // Notes
            GDataEntryContent *content = [contact content];
            NSString *notes = @"";
            if (content && [content contentStringValue]) {
                notes = [content contentStringValue];
                NSLog(@"Notes   :  %@", notes);
            }
 
            if (!ContactName || !(ContactEmail || ContactPhone) ) {
                NSLog(@"Empty Contact Fields. Not Adding.");
            }
            else
            {
                NSArray *keys = [[NSArray alloc] initWithObjects:@"name", @"emailId", @"phoneNumber", @"address", @"dob", @"notes", nil];
                NSArray *objs = [[NSArray alloc] initWithObjects:ContactName, ContactEmail, ContactPhone, address, dob, notes, 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]];
 
        // YOU HAVE YOUR GOOGLE CONTACTS IN 'googleContacts'. Do whatever you want to do with it.
 
        NSString *message = [[NSString alloc] initWithFormat:@"Fetched %d contacts.", [googleContacts count]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Success!"
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil, nil];
        [alertView show];
    }
 
}
 
@end

Download the full source code using the below link:

Hope it helps………..

Comments (21)

  1. Hitesh H Rajyaguru

    Undefined symbols for architecture x86_64:
    “_OBJC_CLASS_$_GDataQueryContact”, referenced from:
    objc-class-ref in MainScreenViewController.o
    “_OBJC_CLASS_$_GDataServiceGoogleContact”, referenced from:
    objc-class-ref in MainScreenViewController.o
    “_kGDataServiceDefaultUser”, referenced from:
    -[MainScreenViewController getGoogleContacts] in MainScreenViewController.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

  2. Mitu

    I encountered a problem like it was working perfectly for some mail id’s but for some mail id’s its showing “Authentication Failed”. Please help me out.

  3. shailendra

    I did all of the steps, but I’ve encountered some errors:

    1. In ViewController.h at #import “GDataFeedContact.h” and “GDataContacts.h” it says the file can’t be found.

    2. In ViewController.m, at [self getGoogleContacts], [self contactService], and [self setContactFetchTicket:ticket] it says that the “Receiver type ViewController for instance message does not declare a method with selector ..”

    I’m using xcode 5.1.

  4. suleman

    Hi there.. its good to see this static library. But having some issue.
    Getting Below error….
    Undefined symbols for architecture armv7:
    “_OBJC_CLASS_$_GTMOAuth2ViewControllerTouch”, referenced from:
    objc-class-ref in EmailHelperManager.o
    objc-class-ref in LoginViewController.o
    ld: symbol(s) not found for architecture armv7
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

    have you updated the static library for armv7 and armv7s? or it is something else error…?

    Thanks

  5. // Notes
    GDataEntryContent *content = [contact content];
    NSString *notes = @"";
    if (content && [content contentStringValue]) {
        notes = [content contentStringValue];
        NSLog(@"notes   :  %@", notes);
    }
  6. Bea

    Thank you so much for all the help! One last question, is it possible to get the notes I add in my contacts? I can’t find it/get it in the gdata sources.

  7. Hi,

    You can get the address using the following code:

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

    You can also use the following if you need the individual elements instead of the ‘formattedAddress’:

    city, countryName, countryCode, houseName, neighborhood, POBox, postCode, region, street, subregion
  8. Bea

    Hi! Sorry for sorta flooding your responses. I was wondering if you knew how to get other contact details such as primary address, birthdays, etc?

    Thanks! 🙂

  9. Bea

    I got it to work already! THANK YOU SO MUCH FOR THIS TUTORIAL! 😀

  10. Bea

    I did all of the steps, but I’ve encountered some errors:

    1. In ViewController.h at #import “GDataFeedContact.h” and “GDataContacts.h” it says the file can’t be found.

    2. In ViewController.m, at [self getGoogleContacts], [self contactService], and [self setContactFetchTicket:ticket] it says that the “Receiver type ViewController for instance message does not declare a method with selector ..”

    I’m using xcode 4.2 cause my mac is only on snow leopard.

    I’m new to xcode, so this tutorial is really appreciated! Thank you for all the help! 🙂

  11. Jitendra Deore

    I have used the Login with Gmail in my ios app. when user click with gmail login default gmail login window will be open in webview. where user can write therir username and password. and then after login succeessfully access to main view controller.

    but in you app need to pass the user name and password to get the gmail contact. so how can i do this with my app.

  12. The source you download have all google service.
    I have complied and created the library for Google contacts. Thats the one i have given in the post.

  13. Tristan

    This is great, thanks! I was just wondering where you got the GData library (or how you created it)?

Leave a comment

Your email address will not be published.

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.