I fetch contact in addressbook iphone 4s not working - iphone

+(NSMutableArray *)getLastName
{
ABAddressBookRef addressBook = ABAddressBookCreate();
NSMutableArray *lastNameArray = [[NSMutableArray alloc]init];
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFIndex numberOfContacts = ABAddressBookGetPersonCount(addressBook);
NSLog(#"%ld",numberOfContacts);
CFArrayRef people = (__bridge CFArrayRef)((__bridge NSArray*)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByLastName));
NSArray * tempArray = [[NSArray alloc]init];
tempArray = (__bridge NSArray *)(people);
if ([tempArray count]>0) {
for (int personIndex = 0; personIndex < [tempArray count]-1; personIndex++) {
ABRecordRef person = (__bridge ABRecordRef)([tempArray objectAtIndex:personIndex]);
ABMultiValueRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *lastNameString = (__bridge NSString *)lastName;
if (lastName!=nil)
[lastNameArray addObject:lastNameString];
}
}
return lastNameArray;
}
I am using the xcode 6.0. iphone 3s is working fine but iphone 4s and iphone 5 not working in that code

-(void)_addContactToAddressBook
{
char *lastNameString, *firstNameString,*emailString;
NSMutableArray *arrname =[[NSMutableArray alloc] init];
NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
// AddressBook
ABAddressBookRef ab = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(ab);
CFIndex nPeople = ABAddressBookGetPersonCount(ab);
for(int i = 0; i < nPeople; i++)
{
[dict removeAllObjects];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonEmailProperty);
CFStringRef email;
if (ABMultiValueGetCount(multi) > 0) {
// collect all emails in array
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(multi, i);
//[personDealingWithEmails addObject:(NSString *)emailRef];
email=emailRef;
CFRelease(emailRef);
}
}
else
{
email=nil;
}
CFDataRef imgData;
if(ABPersonHasImageData(ref))
{
imgData = ABPersonCopyImageData(ref);
}else {
imgData=nil;
}
static char* fallback = "";
int fbLength = strlen(fallback);
int firstNameLength = fbLength;
bool firstNameFallback = true;
int lastNameLength = fbLength;
bool lastNameFallback = true;
int emailLength = fbLength;
bool emailFallback = true;
if (firstName != NULL)
{
firstNameLength = (int) CFStringGetLength(firstName);
firstNameFallback = false;
}
if (lastName != NULL)
{
lastNameLength = (int) CFStringGetLength(lastName);
lastNameFallback = false;
}
if (email != NULL)
{
emailLength = (int) CFStringGetLength(email);
emailFallback = false;
}
if (firstNameLength == 0)
{
firstNameLength = fbLength;
firstNameFallback = true;
}
if (lastNameLength == 0)
{
lastNameLength = fbLength;
lastNameFallback = true;
}
if (emailLength == 0)
{
emailLength = fbLength;
emailFallback = true;
}
firstNameString = malloc(sizeof(char)*(firstNameLength+1));
lastNameString = malloc(sizeof(char)*(lastNameLength+1));
emailString = malloc(sizeof(char)*(emailLength+1));
if (firstNameFallback == true)
{
strcpy(firstNameString, fallback);
}
else
{
CFStringGetCString(firstName, firstNameString, 10*CFStringGetLength(firstName), kCFStringEncodingASCII);
}
if (lastNameFallback == true)
{
strcpy(lastNameString, fallback);
}
else
{
CFStringGetCString(lastName, lastNameString, 10*CFStringGetLength(lastName), kCFStringEncodingASCII);
}
if (emailFallback == true)
{
strcpy(emailString, fallback);
}
else
{
CFStringGetCString(email, emailString, 10*CFStringGetLength(email), kCFStringEncodingASCII);
}
printf("%d.\t%s %s\n", i, firstNameString, lastNameString);
NSString *fname= [NSString stringWithFormat:#"%s",firstNameString];
NSString *lname= [NSString stringWithFormat:#"%s",lastNameString];
NSString *fullName=[NSString stringWithFormat:#"%#%#%#",fname,([fname length]!=0)?#" ":#"",lname];
NSString *eMail= [NSString stringWithFormat:#"%s",emailString];
NSData *myData;
if (imgData) {
myData=(__bridge NSData *)imgData;
}else {
myData=nil;
}
//fetch Phone num
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(ref, kABPersonPhoneProperty);
NSArray* phoneNumbers = (__bridge NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
CFRelease(phoneNumberProperty);
// Do whatever you want with the phone numbers
//NSLog(#"Phone numbers = %#", phoneNumbers);
NSString *PhoneNum = [phoneNumbers objectAtIndex:0];
//--------------remove special char form string(Phone number)-----------------
NSString *originalString = PhoneNum;
//NSLog(#"%#", originalString);
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
if([fname isEqualToString:#""] && [lname isEqualToString:#""]){
}else{
if (myData) {
UIImage *img = [UIImage imageWithData:myData];
[dict setObject:img forKey:#"imgData"];
}
[dict setValue:fname forKey:#"fname"];
[dict setValue:lname forKey:#"lname"];
[dict setValue:fullName forKey:#"fullName"];
[dict setValue:eMail forKey:#"email"];
[dict setValue:strippedString forKey:#"phoneNumber"];
[dict setValue:#"addressbook" forKey:#"type"];
[arrname addObject:[dict copy]];
}
if (firstName != NULL)
{
CFRelease(firstName);
}
if (imgData != NULL)
{
CFRelease(imgData);
}
if (lastName != NULL)
{
CFRelease(lastName);
}
if (email != NULL)
{
CFRelease(email);
}
free(firstNameString);
free(lastNameString);
free(emailString);
}
for (int i=0; i<[arrname count]; i++)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:#"0" forKey:#"sel"];
[arrTemp addObject:dict];
}
[arrallcontacts addObjectsFromArray:arrname];
[arraddedcontactsfulllist addObjectsFromArray:arrallcontacts];
NSSortDescriptor *sortByfullName = [[NSSortDescriptor alloc] initWithKey:#"fullName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:sortByfullName];
NSArray *sorted = [arraddedcontactsfulllist sortedArrayUsingDescriptors:descriptors];
[arraddedcontactsfulllist removeAllObjects];
[arraddedcontactsfulllist addObjectsFromArray:sorted];
[arraddedcontacts removeAllObjects];
[arraddedcontacts addObjectsFromArray:sorted];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
tblview.alpha=1;
[UIView commitAnimations];
[tblview reloadData];
if (![[[[NSUserDefaults standardUserDefaults] objectForKey:#"USER_DETAIL"] objectForKey:#"facebook"] isEqualToString:#"Unauthenticate"]) {
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[self performSelector:#selector(getfacebookfriends) withObject:nil afterDelay:0.0001];
}
}
-(void)fetchIphoneContact
{
if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0)
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self _addContactToAddressBook];
[tblview reloadData];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self _addContactToAddressBook];
[tblview reloadData];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
DisplayAlertWithTitle(APP_Name, #"You can change your privacy setting in settings app");
}
}
else
{
[self _addContactToAddressBook];
}
}
This will work on iOS6 and lower..

I think the problem is with you iOS version.... If you're using iOS 6.0 then ABAddressBookCreate() won't work... it is fine for iOS 5.1 or before.... so you can do like,
ABAddressBookRef addressBook;
if ([self isABAddressBookCreateWithOptionsAvailable])
{
// iOS 6
CFErrorRef error = nil;
addressBook = ABAddressBookCreateWithOptions(NULL,&error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
});
ABAddressBookRevert(addressBook);
}
else
{
// iOS 4/5
addressBook = ABAddressBookCreate();
}
-(BOOL)isABAddressBookCreateWithOptionsAvailable
{
return &ABAddressBookCreateWithOptions != NULL;
}
By this you can get all contacts...:)

There could be different ways to retrieve AddressBook in IOS but one way which I use to retrieve addressbook is as follows, make sure you are using ABPeoplePickerNavigationControllerDelegate You can open the AddressBook Controller on a button click like this
-(IBAction)getContact:(id)sender {
// creating the picker
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
// place the delegate of the picker to the controll
picker.peoplePickerDelegate = self;
[self presentModalViewController:picker animated:YES];
}
after addressBook is presented you can use the delegate methods to receive the contact information as follows
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
// setting the first name
firstNameTxt.text = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
// setting the last name
lastNameTxt.text = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
// setting the number
/*
this function will set the first number it finds
if you do not set a number for a contact it will probably
crash
*/
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
telefonTxt.text = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, 0);
ABMultiValueRef multi1 = ABRecordCopyValue(person, kABPersonEmailProperty);
emailTxt.text = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi1, 0);
// remove the controller
[self dismissModalViewControllerAnimated:YES];
return NO;
}

Related

Fetch Contacts in iOS 7

This code works fine with iOS5/iOS6 but not working with iOS7.
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
//ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
// NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString *phoneNumber;
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
// NSLog(#"phone:%#", phoneNumber);
}
Today updated my example and removed memory leaks :)
+ (NSArray *)getAllContacts {
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef allPeople = (ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName));
//CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
CFIndex nPeople = CFArrayGetCount(allPeople); // bugfix who synced contacts with facebook
NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
if (!allPeople || !nPeople) {
NSLog(#"people nil");
}
for (int i = 0; i < nPeople; i++) {
#autoreleasepool {
//data model
ContactsData *contacts = [ContactsData new];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//get First Name
CFStringRef firstName = (CFStringRef)ABRecordCopyValue(person,kABPersonFirstNameProperty);
contacts.firstNames = [(__bridge NSString*)firstName copy];
if (firstName != NULL) {
CFRelease(firstName);
}
//get Last Name
CFStringRef lastName = (CFStringRef)ABRecordCopyValue(person,kABPersonLastNameProperty);
contacts.lastNames = [(__bridge NSString*)lastName copy];
if (lastName != NULL) {
CFRelease(lastName);
}
if (!contacts.firstNames) {
contacts.firstNames = #"";
}
if (!contacts.lastNames) {
contacts.lastNames = #"";
}
contacts.contactId = ABRecordGetRecordID(person);
//append first name and last name
contacts.fullname = [NSString stringWithFormat:#"%# %#", contacts.firstNames, contacts.lastNames];
// get contacts picture, if pic doesn't exists, show standart one
CFDataRef imgData = ABPersonCopyImageData(person);
NSData *imageData = (__bridge NSData *)imgData;
contacts.image = [UIImage imageWithData:imageData];
if (imgData != NULL) {
CFRelease(imgData);
}
if (!contacts.image) {
contacts.image = [UIImage imageNamed:#"avatar.png"];
}
//get Phone Numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiPhones); i++) {
#autoreleasepool {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = CFBridgingRelease(phoneNumberRef);
if (phoneNumber != nil)[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
}
if (multiPhones != NULL) {
CFRelease(multiPhones);
}
[contacts setNumbers:phoneNumbers];
//get Contact email
NSMutableArray *contactEmails = [NSMutableArray new];
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
#autoreleasepool {
CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
NSString *contactEmail = CFBridgingRelease(contactEmailRef);
if (contactEmail != nil)[contactEmails addObject:contactEmail];
// NSLog(#"All emails are:%#", contactEmails);
}
}
if (multiEmails != NULL) {
CFRelease(multiEmails);
}
[contacts setEmails:contactEmails];
[items addObject:contacts];
#ifdef DEBUG
//NSLog(#"Person is: %#", contacts.firstNames);
//NSLog(#"Phones are: %#", contacts.numbers);
//NSLog(#"Email is:%#", contacts.emails);
#endif
}
} //autoreleasepool
CFRelease(allPeople);
CFRelease(addressBook);
CFRelease(source);
return items;
}
Actually recently wrote pod in Swift 3 using CNContacts, to whom it may need
Swift ContactBook Picker
Didn't write it myself. But it works with me:
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
ABAddressBookRef addressBook = ABAddressBookCreate( );
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
// NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
// NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
// NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
[[UIDevice currentDevice] name];
//NSLog(#"\n%#\n", [[UIDevice currentDevice] name]);
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
addressBookNum = [addressBookNum stringByAppendingFormat: #":%#",phoneNumber];
}
}
NSLog(#"AllNumber:%#",addressBookNum);
}
else {
// Send an alert telling user to change privacy setting in settings app
}
and in my .h
#property NSString * addressBookNum;

IOS AddressBook is not fetching all the phone number from contact list

I am using Addressbook in my IOS app to fetch the contact name and numbers, but a strange thing is happening that it is showing phone number of some of the contacts.
I was hoping it will show all the contact list with phone number.
so here is my code to fetch phone numbers:
-(void)getAddressbookData
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000
ABAddressBookRef addressBook = ABAddressBookCreate();
#else
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
#endif
NSArray * people;
BOOL accessGranted = [self __addressBookAccessStatus:addressBook];
if (accessGranted)
{
people = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
// Do whatever you need with thePeople...
}
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray *contactArray = [[NSMutableArray alloc] init];
for (CFIndex i = 0; i < nPeople; i++)
{
ABRecordRef record = CFArrayGetValueAtIndex((__bridge CFArrayRef)(people), i);
NSString *firstName = (__bridge NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
NSString *fullName = nil;
if (ABPersonGetCompositeNameFormat() == kABPersonCompositeNameFormatFirstNameFirst)
fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
else
fullName = [NSString stringWithFormat:#"%#, %#", lastName, firstName];
[contactArray addObject:fullName];
//
// Phone Numbers
//
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(record, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );
NSMutableArray *numbersArray = [[NSMutableArray alloc] init];
for ( CFIndex k=0; k<phoneNumberCount; k++ )
{
CFStringRef phoneNumberLabel = ABMultiValueCopyLabelAtIndex( phoneNumbers, k );
CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex( phoneNumbers, k );
CFStringRef phoneNumberLocalizedLabel = ABAddressBookCopyLocalizedLabel( phoneNumberLabel );
// converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
// Find the ones you want here
//
// NSLog(#"-----PHONE ENTRY -> name:%# : %# : %#", fullName, phoneNumberLocalizedLabel, phoneNumberValue );
[numbersArray addObject:CFBridgingRelease(phoneNumberValue)];
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
}
// NSLog(#"phone numbers %#", numbersArray);
[contactDictionary setObject:numbersArray forKey:fullName];
CFRelease(record);
}
selectContacts = contactArray;
// NSLog(#"dictionary of array %#", contactDictionary);
//NSLog(#"contacts count %d", [selectContacts count]);
}
-(BOOL)__addressBookAccessStatus:(ABAddressBookRef) addressBook
{
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
// dispatch_release(sema);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
return accessGranted;
}
so numbersArray is blank for some of the contacts I dont know why it is happening.
try this for phone no.
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
for(id person in people){
//fetch multiple phone nos.
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++) {
NSString* phone = (NSString*)ABMultiValueCopyValueAtIndex(multi, j);
[numbersArray addObject:phone];
[phone release];
}
}
and you have to alloc your array before you use. in viewDidLoad method write this for alloc array
numbersArray=[[NSMutableArray alloc] init];
I am using this code to access the mobile number from my address book and its working fine.
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allSources = ABAddressBookCopyArrayOfAllPeople( addressBook );
for (CFIndex i = 0; i < ABAddressBookGetPersonCount( addressBook ); i++)
{
ABRecordRef aSource = CFArrayGetValueAtIndex(allSources,i);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(aSource, kABPersonPhoneProperty);
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
home_mobile = [(NSString*)ABMultiValueCopyValueAtIndex(phones, i) retain];
}
if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
basic_mobile = [(NSString*)ABMultiValueCopyValueAtIndex(phones, i)retain];
}
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMainLabel])
{
work_mobile = [(NSString*)ABMultiValueCopyValueAtIndex(phones, i)retain];
}
}
You can try this.
Here's the Swift version of #Samir's answer which worked for me.
var allNumbers: [AnyObject] = []
let adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
let people = ABAddressBookCopyArrayOfAllPeople(adbk).takeRetainedValue() as NSArray as [ABRecord]
for person in people {
var phones: ABMultiValueRef = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
for j in 0..<ABMultiValueGetCount(phones) {
var phone: String = ABMultiValueCopyValueAtIndex(phones, j).takeRetainedValue() as String
allNumbers.append(phone)
}
}
println(allNumbers)

iOS - how to selectively import/export iPad contacts with application contact

I want to create an application which should add selected contacts from iPad device to your iPad application
i am new to ios so i am not getting proper help from google
can someone help me form some article or references to do such application .
Thanks for your Help,
Arun
First Add all Delegate and Datasource method in your class .h file
<ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate,ABNewPersonViewControllerDelegate,ABUnknownPersonViewControllerDelegate>
Create ABPeoplePickerNavigationController
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
// Show the picker
[self presentModalViewController:picker animated:YES];
[picker release];
Add Following Delegate and DataSource method of ABPeopelPickerNavigationController
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
return YES;
}
please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
}
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
For more information read this and this tutorial.
Thanks :)

Adding address book in contact page

I want to add an address book in my contact page and I want to do that programmatically i.e without using nib files. Can anyone suggest me a nice tutorial or sample code for that. i have used the codes of the answer given by iPatel and when i am running it is throwing exception and app is getting terminated.
thanks and regards.
Here is the edited code.
#import "ContactInfoViewController.h"
#interface ContactInfoViewController ()
#end
#implementation ContactInfoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor yellowColor];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(gotohomepage:)]autorelease];
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (IBAction)gotohomepage:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
EDIT :
First Add all Delegate and Datasource method in your class .h file
<ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate,ABNewPersonViewControllerDelegate,ABUnknownPersonViewControllerDelegate>
Create ABPeoplePickerNavigationController
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
// Show the picker
[self presentModalViewController:picker animated:YES];
[picker release];
Add Following Delegate and DataSource method of ABPeopelPickerNavigationController
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
return YES;
}
please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
}
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
For more information read this and this tutorial.
Thanks :)

Accessing all the email IDs for each contact from the iphone contactlist through code

I am new to iphone.presently i am working in project but i have struck in the middle of the project because of don't know how to access all the email id's for each contact from the iphone contactlist through coding.if anybody knows about this concept can you please help me....
this code gives u email along with their display names and contact name too
-(NSMutableArray*)getEmailAndPhoneOfPhoneContacts
{
NSLog(#"getPhoneContacts");
NSAutoreleasePool *pool= [[NSAutoreleasePool alloc] init];
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
ABAddressBookRef iPhoneAddressBook=ABAddressBookCreate();
if(!iPhoneAddressBook)
{
DLog(#"unable to open addressBook");
}
//ABPerson *newPerson;
NSAutoreleasePool *innerPool=nil;
CFArrayRef allPeople=ABAddressBookCopyArrayOfAllPeople(iPhoneAddressBook);
NSMutableArray *peopleArray=[NSMutableArray arrayWithArray:(NSMutableArray*)allPeople];
BOOL shouldReleasePool=NO;
NSInteger i;
for(i=0;i<[peopleArray count];i++)
{
if((i&255)==0)
{
innerPool= [[NSAutoreleasePool alloc] init];
shouldReleasePool=YES;
}
ABRecordRef record=[peopleArray objectAtIndex:i];
Contact *objPhoneContact=[[Contact alloc] init];
objPhoneContact.contactType=STATIC_CONTACT;
CFStringRef prefixName=ABRecordCopyValue(record, kABPersonPrefixProperty);
CFStringRef firstName=ABRecordCopyValue(record, kABPersonFirstNameProperty);
CFStringRef middleName=ABRecordCopyValue(record, kABPersonMiddleNamePhoneticProperty);
CFStringRef lastName=ABRecordCopyValue(record, kABPersonLastNameProperty);
CFStringRef suffixName=ABRecordCopyValue(record, kABPersonSuffixProperty);
NSMutableString *contactname =[[NSMutableString alloc] init];
// concating all the names
if (prefixName) {
[contactname appendString:[NSString stringWithString:(NSString*)prefixName]];
CFRelease(prefixName);
}
if (firstName) {
[contactname appendString:[NSString stringWithString:(NSString*)firstName]];
CFRelease(firstName);
}
if (middleName) {
[contactname appendString:[NSString stringWithString:(NSString*)middleName]];
CFRelease(middleName);
}
if (lastName) {
[contactname appendString:[NSString stringWithString:(NSString*)lastName]];
CFRelease(lastName);
}
if (suffixName) {
[contactname appendString:[NSString stringWithString:(NSString*)suffixName]];
CFRelease(suffixName);
}
// if emty then get the organization property
if (contactname == nil || [contactname length]<1) {
CFStringRef orgName=ABRecordCopyValue(record, kABPersonOrganizationProperty);
if (orgName) {
[contactname appendString:[NSString stringWithString:(NSString*)orgName]];
CFRelease(orgName);
}
}
//if still empty then assign (no name) to it
if (contactname == nil || [contactname length]<1)
[contactname setString:#"(no name)"];
objPhoneContact.mContactName = [contactname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[contactname release];
contactname = nil;
ABMutableMultiValueRef multi;
int multiCount=0;
multi=ABRecordCopyValue(record,kABPersonEmailProperty);
NSUInteger emailIndex_home=301;
NSUInteger emailIndex_work=321;
NSUInteger emailIndex_other=341; //~400
multiCount=ABMultiValueGetCount(multi);
if(multiCount ==0)
{
//objPhoneContact.mEmailId=#"";
}
else
{
for( int i=0; i < multiCount; i++)
{
ContactProperty* objEmailContactProperty=[[ContactProperty alloc] init];
objEmailContactProperty.mContactPropertyString=(NSString*)ABMultiValueCopyValueAtIndex(multi, i);
objEmailContactProperty.mDisplayName=(NSString*)ABMultiValueCopyLabelAtIndex(multi, i);
objEmailContactProperty.mDisplayName=[objEmailContactProperty.mDisplayName stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"_$!<>"]];
if([objEmailContactProperty.mDisplayName caseInsensitiveCompare:#"home"]==NSOrderedSame)
{
objEmailContactProperty.mContactPropId=emailIndex_home;
emailIndex_home++;
}
else if([objEmailContactProperty.mDisplayName caseInsensitiveCompare:#"work"]==NSOrderedSame)
{
objEmailContactProperty.mContactPropId=emailIndex_work;
emailIndex_work++;
}
/*
else if([objEmailContactProperty.mDisplayName caseInsensitiveCompare:#"other"]==NSOrderedSame)
{
objEmailContactProperty.mContactPropId=[NSString stringWithFormat:#"%d",emailIndex_other];
emailIndex_other++;
}
*/
else
{
objEmailContactProperty.mContactPropId=emailIndex_other;
emailIndex_other++;
}
objEmailContactProperty.mContactDataType=#"Email";
[objPhoneContact.mPropertyArray addObject:objEmailContactProperty];
[objEmailContactProperty release];
}
}
if(multi)
CFRelease(multi);
[tempArray addObject:objPhoneContact];
[objPhoneContact release];
if(shouldReleasePool)
{
[innerPool drain];
shouldReleasePool=NO;
}
}
self.mPhoneContactArray=tempArray;
CFRelease(iPhoneAddressBook);
CFRelease(allPeople);
[pool drain];
return [tempArray autorelease];
}
Make sure you import these two files:
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
-(IBAction)showPeoplePickerController
{
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
[menuArray removeAllObjects];
if(menuArray ==nil)
menuArray = [[NSMutableArray alloc] init];
for (int i = 0; i < nPeople; i++)
{
NSMutableDictionary *localDic=[[NSMutableDictionary alloc]init];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
ABRecordID recordId = ABRecordGetRecordID(ref);
[localDic setObject:[NSString stringWithFormat:#"%d",recordId] forKey:#"Record_Id"];
//get firstname
CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
[localDic setObject:[NSString stringWithFormat:#"%#",firstName] forKey:#"first_name"];
//get lastname
CFStringRef lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
[localDic setObject:[NSString stringWithFormat:#"%#",lastName] forKey:#"last_name"];
NSString *contactFirstLast = [NSString stringWithFormat: #"%# %#",firstName,lastName];
[localDic setObject:contactFirstLast forKey:#"FullName"];
//get EmailIds
ABMutableMultiValueRef EmailIds = ABRecordCopyValue(ref, kABPersonEmailProperty);
CFTypeRef EmailId;
NSString *EmailLabel;
for (CFIndex i = 0; i < ABMultiValueGetCount(EmailIds); i++) {
EmailLabel=[NSString stringWithFormat:#"%#",ABMultiValueCopyLabelAtIndex(EmailIds,i)];
if([EmailLabel isEqualToString:#"_$!<Home>!$_"])
{
EmailId = ABMultiValueCopyValueAtIndex(EmailIds,i);
[localDic setObject:[NSString stringWithFormat:#"%#",EmailId] forKey:#"Email_Home"];
}
else if([EmailLabel isEqualToString:#"_$!<Work>!$_"])
{
EmailId = ABMultiValueCopyValueAtIndex(EmailIds,i);
[localDic setObject:[NSString stringWithFormat:#"%#",EmailId] forKey:#"Email_Work"];
break;
}
}
[menuArray addObject:localDic];
}
NSLog(#"%#",menuArray);
}
In this way you get all EmailIds of each people.
and also add these two frameworks in your project:
AddressBook.framework
AddressBookUI.framework