ABAddressBook store values in NSDictionary - iphone

I have an app that displays ABAddressBook contacts in a UITableView. Currently I'm reading the contacts into an NSDictionary, however this appears to crash for some users, which I suspect is a memory issue.
Is there another approach to display ABAddressBook contacts in a UITableView without either first storing them in an NSDictionary or using ABPeoplePicker?

A different way using ARC:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef addressBookData = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex count = CFArrayGetCount(addressBookData);
NSMutableArray *contactsArray = [NSMutableArray new];
for (CFIndex idx = 0; idx < count; idx++) {
ABRecordRef person = CFArrayGetValueAtIndex(addressBookData, idx);
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
if (firstName) {
NSDictionary *dict = [NSDictionary dictionaryWithObject:firstName ForKey:#"name"];
[contactsArray addObject:dict];
}
}
CFRelease(addressBook);
CFRelease(addressBookData);

You can use following way,
ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, NULL);
NSArray *arrTemp = (NSArray *)ABAddressBookCopyArrayOfAllPeople(ab);
The above 2 lines will create an array for all your contacts on the iPhone.
Now whatever property of a contact you want to display you can display by using the below code. For example, I want to display the first name of all contacts and then create one Mutable array called it arrContact.
NSMutableArray *arrContact = [[NSMutableArray alloc] init];
for (int i = 0; i < [arrTemp count]; i++)
{
NSMutableDictionary *dicContact = [[NSMutableDictionary alloc] init];
NSString *str = (NSString *) ABRecordCopyValue([arrTemp objectAtIndex:i], kABPersonFirstNameProperty);
#try
{
[dicContact setObject:str forKey:#"name"];
}
#catch (NSException * e) {
[dicContact release];
continue;
}
[arrContact addObject:dicContact];
[dicContact release];
}
Now just display it using the arrContact array in a table view..

Same as Abizern's answer, but if you want to display full names that are localized, use ABRecordCopyCompositeName. (In English names are "First Last", but in Chinese names are "LastFirst").
ABRecordRef person = CFArrayGetValueAtIndex(addressBookData, idx);
NSString *fullName = (__bridge_transfer NSString *)ABRecordCopyCompositeName(person);//important for localization

Related

keys values in array like array[0] and so on

I am using this code
NSDictionary *yourDictionary;
NSArray * yourKeys;
yourKeys = [yourDictionary allValues];
to get the value of dictionary. But i want that array output in this form : array[0] ,array[1] while I am getting the output in console as below:-
2013-01-12 18:44:10.213 Birthday_Reminder[2871:c07] (
{
},
"Arpit Sihare")
and so on values.
so plz help me to get those values in this form and also I'm using KABPersonfirstnameproperty to retrieve those name from address book.
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray* allPeoplesDicts = [NSMutableArray array];
for (id person in thePeople)
{
ABMultiValueRef phone =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* name = (NSString *)ABRecordCopyCompositeName(person);
// NSMutableArray* phones = [[NSMutableArray alloc] init];
NSDictionary *phones=[[NSDictionary alloc]init ];
for (CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
NSString *phone = [(NSString *)ABMultiValueCopyValueAtIndex(phones,i) autorelease];
[phones addObject:phone];
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys:name,#"Name",phones,#"PhoneNumbers",nil];
[phones release];
NSArray * yourKeys;
yourKeys = [personDict allValues];
NSLog(#"%#",yourKeys);
[allPeoplesDicts addObject:personDict];
[personDict release];
}
and I want firstname in array form that when i use nslog(#"%#",array[0]) it should print value stored in array first place and soon like array[1]....
It's too hard to understand what you are trying to say. I tried and found...
If you just want to store all the firstName (which is your key I think) then just make yourKeys an NSMutableArray and add the names to that Array. :
[yourKeys addObject:names];
Simple !!

How to get contacts detail of iphone and make CSV file of that contact

I want to get contact details in an iPhone with information like First Name, Last Name, Phone Number, Phone Number Type, Email Address, Email Address Type etc..
Can anyone help me with that?
I want to make a .csv file out of the contact details in a particular iPhone. I want to fetch iPhone address book data.
Following is the code to get all informations of iPhone contact book...
-(void)collectContacts
{
NSMutableDictionary *myAddressBook = [[NSMutableDictionary alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
// Get First name, Last name, Prefix, Suffix, Job title
NSString *firstName = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(ref,kABPersonLastNameProperty);
NSString *prefix = (NSString *)ABRecordCopyValue(ref,kABPersonPrefixProperty);
NSString *suffix = (NSString *)ABRecordCopyValue(ref,kABPersonSuffixProperty);
NSString *jobTitle = (NSString *)ABRecordCopyValue(ref,kABPersonJobTitleProperty);
[myAddressBook setObject:firstName forKey:#"firstName"];
[myAddressBook setObject:lastName forKey:#"lastName"];
[myAddressBook setObject:prefix forKey:#"prefix"];
[myAddressBook setObject:suffix forKey:#"suffix"];
[myAddressBook setObject:jobTitle forKey:#"jobTitle"];
NSMutableArray *arPhone = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex(phones, j));
NSString *phoneNumber = (NSString *)phoneNumberRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:phoneNumber forKey:#"phoneNumber"];
[temp setObject:phoneLabel forKey:#"phoneNumber"];
[arPhone addObject:temp];
[temp release];
}
[myAddressBook setObject:arPhone forKey:#"Phone"];
[arPhone release];
CFStringRef address;
CFStringRef label;
ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonAddressProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
CFStringRef readableLabel = ABAddressBookCopyLocalizedLabel(label);
address = ABMultiValueCopyValueAtIndex(multi, i);
CFRelease(address);
CFRelease(label);
}
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *arEmail = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++)
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(emails, idx);
NSString *strLbl = (NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex (emails, idx));
NSString *strEmail_old = (NSString*)emailRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:strEmail_old forKey:#"strEmail_old"];
[temp setObject:strLbl forKey:#"strLbl"];
[arEmail addObject:temp];
[temp release];
}
[myAddressBook setObject:arEmail forKey:#"Email"];
[arEmail release];
}
[self createCSV:myAddressBook];
}
-(void) createCSV :(NSMutableDictionary*)arAddressData
{
NSMutableString *stringToWrite = [[NSMutableString alloc] init];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[arAddressData valueForKey:#"firstName"]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[arAddressData valueForKey:#"lastName"]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[arAddressData valueForKey:#"jobTitle"]]];
//[stringToWrite appendString:#"fname, lname, title, company, phonetype1, value1,phonetype2,value,phonetype3,value3phonetype4,value4,phonetype5,value5,phonetype6,value6,phonetype7,value7,phonetype8,value8,phonetype9,value9,phonetype10,value10,email1type,email1value,email2type,email2value,email3type,email3‌​value,email4type,email4value,email5type,email5value,website1,webs‌​ite2,website3"];
NSMutableArray *arPhone = (NSMutableArray*) [arAddressData valueForKey:#"Phone"];
for(int i = 0 ;i<[arPhone count];i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [arPhone objectAtIndex:i];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[temp valueForKey:#"phoneNumber"]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[temp valueForKey:#"phoneNumber"]]];
[temp release];
}
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *strBackupFileLocation = [NSString stringWithFormat:#"%#/%#", documentDirectory,#"ContactList.csv"];
[stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
I used iApple's code above as a starting point and created a working version from it - this one just collects all address book entries in an array. As mentioned above the original iApple doesn't work, there's a few bugs in it. This one works, and was tested.
Note: This doesn't return any contacts that don't have a name set - you can remove that for your own code, I just did it because I only need contacts with names set, and NSMutableDictionary doesn't like nil entries (crashes).
In my own address book I have a few entries that are just an email - I am not sure how they got there, but it's certainly possible to have address book entries without a name. Keep that in mind when iterating over an address book.
I am using the full name as per Apple's recommendations - ABRecordCopyCompositeName returns a composite of first and last name in the order specified by the user.
Finally, I made this a static method and put it in a helper class.
This is for use with ARC!
// returns an array of dictionaries
// each dictionary has values: fullName, phoneNumbers, emails
// fullName is a string
// phoneNumbers is an array of strings
// emails is an array of strings
+ (NSArray *)collectAddressBookContacts {
NSMutableArray *allContacts = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
NSMutableDictionary *aPersonDict = [[NSMutableDictionary alloc] init];
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *fullName = (__bridge NSString *) ABRecordCopyCompositeName(ref);
if (fullName) {
[aPersonDict setObject:fullName forKey:#"fullName"];
// collect phone numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
NSString *phoneNumber = (__bridge NSString *) ABMultiValueCopyValueAtIndex(phones, j);
[phoneNumbers addObject:phoneNumber];
}
[aPersonDict setObject:phoneNumbers forKey:#"phoneNumbers"];
// collect emails - key "emails" will contain an array of email addresses
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *emailAddresses = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++) {
NSString *email = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emails, idx);
[emailAddresses addObject:email];
}
[aPersonDict setObject:emailAddresses forKey:#"emails"];
// if you want to collect any other info that's stored in the address book, it follows the same pattern.
// you just need the right kABPerson.... property.
[allContacts addObject:aPersonDict];
} else {
// Note: I have a few entries in my phone that don't have a name set
// Example one could have just an email address in their address book.
}
}
return allContacts;
}
First you will need to use the address book framework so this must be added to your Xcode project.
Next you will need to break the task down into a couple steps.
1) Get the people inside the address book
2) Create your .csv file. I'm assuming you know something about CSV file formatting using characters to separate fields and when to add return characters so you have a properly formatted file. This is probably left for another question thread if you need help with this.
3) Save your .csv file somewhere
1) To get an array of all people in the address book you would do something like the following. The reference documentation for ABAddressBook is here. It should be very helpful in helping you access the data.
ABAddressBook *sharedBook = [ABAddressBook sharedAddressBook];
NSArray *peopleList = [sharedBook people];
2) You will have to iterate through each of the people and build your overall csv data. Usually you would manually create the csv data in an NSString and then convert it to NSData and save the NSData to a file. This is not ideal if you are dealing with a really large set of data. If this is the case then you would probably want some code to write your csv data to the file in chunks so you can free memory as you go. For simplicity sake my code just shows you creating the full file then saving the whole works.
NSString *csvString = #"";
for(ABPerson *aPerson in peopleList) {
//Do something here to write each property you want to the CSV file.
csvString = [csvString stringByAppendingFormat:#"'%#',"
[aPerson valueForProperty:kABFirstNameProperty]];
}
NSData *csvData = [csvString dataUsingEncoding:NSUTF8StringEncoding];
3) Write you file to somewhere
//This is an example of writing your csv data to a file that will be saved in the application's sand box directory.
//This file could be extracted using iTunes file sharing.
//Get the proper path to save the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"my_file.csv"];
//Actually write the data
BOOL isSuccessful = [csvData writeToFile:fullPath atomically:NO];
if(isSuccessful) {
//Do something if the file was written
} else {
//Do something if there was an error writing the file
}
See Adress Book API particulary Importing and Exporting Person and Group Records
chack also the Address Book Test example in this blog

checking whether the number is in phone contacts are not

i want to check whether the given number is in phone book or not programatically .
i am able to display the contact name of the given number if it is exists in phone book but the program crashes when there is no contact with that number in phone book ...
but what i want is to display name if it exists in phone book..... and display the number if if is not in phone book......
and my code is as follows....
NSMutableArray *names = [[NSMutableArray alloc] init];
NSMutableArray *phonenumbers = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSString *name;
for (id person in thePeople)
{
name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSLog(#"!!!!!! name ---> %#",name);
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
int count1=ABMultiValueGetCount(multi);
NSLog(#"%d",count1);
if ([name length]>0 && count1!=0)
{
NSString *beforenumber = (NSString *)ABMultiValueCopyValueAtIndex(multi, 0);
NSLog(#" contacts:%#",beforenumber );
NSString* removed1=[beforenumber stringByReplacingOccurrencesOfString:#"-"withString:#""];
NSString* removed2=[removed1 stringByReplacingOccurrencesOfString:#")"withString:#""];
NSString* removed3=[removed2 stringByReplacingOccurrencesOfString:#" "withString:#""];
NSString* removed4=[removed3 stringByReplacingOccurrencesOfString:#"("withString:#""];
NSString* removed5=[removed4 stringByReplacingOccurrencesOfString:#"+"withString:#""];
[names addObject:name];
[phonenumbers addObject:removed5];
}
}
int barindex = -1;
barindex = [phonenumbers indexOfObject:number];
if(barindex == -1)
return number;
else
return [names objectAtIndex:barindex];
can any one please help me how to do that.............
thank you.......
The code would be improved but I think that is what you need.
Sample Code

Search ABAddressbook iOS SDK

I want to search the iPhone address book for a specific phone number, and then retrieve the contact name. I am currently looping through all contacts and extracting the multivalue properties and comparing against the value. This is taking way too much time. I have read the Apple addressbook guide, and they say:
"accomplish other kinds of searches, use the function
ABAddressBookCopyArrayOfAllPeople and then filter the results using
the NSArray method filteredArrayUsingPredicate:."
Can anyone give me an example on how to exactly do that?
Thanks.
If you want to do a search in the contacts with phone number, then I will tell you one suggestion.
1.Get all contacts
NSArray *thePeoples = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
2.Create another array(records) from the contacts array(thePeoples),
records:[
record1, record2, ....recordN ]
record: {name:"myContactName",
phoneNumber:"1234567890"}
3.Search the mutableArray(records) with predicate.
NSPredicate * myPredicate = [NSPredicate predicateWithFormat:#"record.phoneNumber contains %#",string];
NSArray * filteredArray = [records filteredArrayUsingPredicate:myPredicate];
This is just a simple example to your solution, and remember phoneNumber is a multiValue field. So we will include an array as phone number in the model class variable.
The following method will return an array that contains all of the contacts that have the given phone number. This method took 0.02 seconds to search 250 contacts on my iPhone 5 running iOS7.
#import <AddressBook/AddressBook.h>
-(NSArray *)contactsContainingPhoneNumber:(NSString *)phoneNumber {
/*
Returns an array of contacts that contain the phone number
*/
// Remove non numeric characters from the phone number
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:#""];
// Create a new address book object with data from the Address Book database
CFErrorRef error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (!addressBook) {
return [NSArray array];
} else if (error) {
CFRelease(addressBook);
return [NSArray array];
}
// Requests access to address book data from the user
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {});
// Build a predicate that searches for contacts that contain the phone number
NSPredicate *predicate = [NSPredicate predicateWithBlock: ^(id record, NSDictionary *bindings) {
ABMultiValueRef phoneNumbers = ABRecordCopyValue( (__bridge ABRecordRef)record, kABPersonPhoneProperty);
BOOL result = NO;
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
NSString *contactPhoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
contactPhoneNumber = [[contactPhoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:#""];
if ([contactPhoneNumber rangeOfString:phoneNumber].location != NSNotFound) {
result = YES;
break;
}
}
CFRelease(phoneNumbers);
return result;
}];
// Search the users contacts for contacts that contain the phone number
NSArray *allPeople = (NSArray *)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSArray *filteredContacts = [allPeople filteredArrayUsingPredicate:predicate];
CFRelease(addressBook);
return filteredContacts;
}
Use This. this is my code.
Make Array for searching.
NSLog(#"=====Make People Array with Numbers. Start.");
peopleWithNumber = [[NSMutableDictionary alloc] init];
for (int i=0; i < [people count]; i++) {
NSInteger phoneCount = [self phoneCountAtIndex:i];
if (phoneCount != 0) {
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
for (int j=0 ; j < phoneCount ; j++) {
[phoneNumbers addObject:[self phoneNumberAtIndex:i phoneIndex:j]];
}
[peopleWithNumber addEntriesFromDictionary:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithArray:phoneNumbers], [self fullNameAtIndex:i], nil]];
}
}
NSLog(#"=====Make People Array with Numbers. End.\n");
Searching method. it(peopleWithNumber) would be faster than using array(people)
"NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);"
- (NSArray *)searchNamesByNumber:(NSString *)number {
NSString *predicateString = [NSString stringWithFormat:#"%#[SELF] contains '%#'",#"%#",number];
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:predicateString,peopleWithNumber,number];
NSArray *names = [[peopleWithNumber allKeys] filteredArrayUsingPredicate:searchPredicate];
return names;
}
You cannot use a predicateWithFormat with an array of ABRecordRef opaque types. But you can use predicateWithBlock:
[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
ABRecordRef person=(__bridge ABRecordRef)evaluatedObject;
CFTypeRef theProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSArray *phones = (__bridge_transfer NSArray *) ABMultiValueCopyArrayOfAllValues(theProperty);
CFRelease(theProperty);
BOOL result=NO;
for (NSString *value in phones) {
if ([value rangeOfString:#"3"].location!=NSNotFound) {
result=YES;
break;
}
}
return result;
}];

Getting iPhone addressbook contents without GUI

I would like to list all phone numbers (or any other field) of people in the addressbook.
I've written the following code:
- (void)addressBookFill{
ABAddressBookRef addressBook = ABAddressBookCreate();
people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
[addressBook release];
}
- (void)printAddressBook{
for(id person in people){
NSLog(#"%#", [person class]);
NSLog(#"\t%#", person );
}
}
When I invoke the printAddressBook method I get this on my console:
2010-07-06 10:34:11.998 app[91420:207] __NSCFType
2010-07-06 10:34:11.999 app[91420:207] <CPRecord: 0x5d56ce0 ABPerson>
And I don't have any idea, how to dereference this ABPerson object, how to get any info from it.
I tried:
firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
but I got some exceptions.
Can anybody tell me how to get some info from these objects?
Read the documentation about the ABPerson class:
http://developer.apple.com/mac/library/documentation/UserExperience/Reference/AddressBook/Classes/ABPerson_Class/Reference/Reference.html
and also the ABRecord class:
http://developer.apple.com/mac/library/documentation/UserExperience/Reference/AddressBook/Classes/ABRecord_Class/Reference/Reference.html#//apple_ref/occ/cl/ABRecord
[ person valueForProperty: #"propName" ]
You can get the available properties with:
[ ABPerson properties ]
[ EDIT ]
On iPhone, you can use the following code to access a value:
NSString * lastName = (NSString *)ABRecordCopyValue( person, kABPersonLastNameProperty );
May be this code will help you for iOS5, please like it
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;peopleCounter < [arrayOfAllPeople count]; peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef) [arrayOfAllPeople objectAtIndex:peopleCounter];
NSString *name = (__bridge_transfer NSString *) ABRecordCopyCompositeName(thisPerson);
NSLog(#"First Name = %#", name);
ABMultiValueRef emails = ABRecordCopyValue(thisPerson, kABPersonEmailProperty);
for (NSUInteger emailCounter = 0; emailCounter < ABMultiValueGetCount(emails); emailCounter++){
/* And then get the email address itself */
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, emailCounter);
NSLog(#"Email : %#",email);
}
}
CFRelease(addressBook);
You want get only those contact who has email on my contact so use this code for iOS5
Please like it if it work
First add AddressBook.framework and #import <AddressBook/AddressBook.h>
- (NSArray*)printAddressBook{
NSMutableArray *mutableData = [NSMutableArray new];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;peopleCounter < [arrayOfAllPeople count]; peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef) [arrayOfAllPeople objectAtIndex:peopleCounter];
NSString *name = (__bridge_transfer NSString *) ABRecordCopyCompositeName(thisPerson);
NSLog(#"First Name = %#", name);
ABMultiValueRef emails = ABRecordCopyValue(thisPerson, kABPersonEmailProperty);
for (NSUInteger emailCounter = 0; emailCounter < ABMultiValueGetCount(emails); emailCounter++){
/* And then get the email address itself */
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, emailCounter);
NSLog(#"Email : %#",email);
NSMutableDictionary *personDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:name,#"name",email,#"email", nil];
[mutableData addObject:personDict];
}
}
CFRelease(addressBook);
return [NSArray arrayWithArray:mutableData];
}