How to get contact information about iphone and make CSV file of this contact

I want to get contact information on the iPhone with information such as First Name, Last Name, Phone Number, Phone Number Type, Email Address, Email Address Type, etc.

Can anyone help me with this?

I want to make a CSV file from contact information in a specific iPhone. I want to get the address book information for iPhone.

+8
iphone csv
source share
4 answers

Below is the code to get all the contact information for iPhone ...

-(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]; } 
+13
source share

I used the iApple code above as a starting point and created a working version from it - this one only collects all the entries in the address book in an array. As mentioned above, the original iApple does not work, there are several errors. This works and is tested.

Note. This does not return any contacts that do not have a given name, you can delete them for your own code, I just did it because I only need contacts with name sets, and NSMutableDictionary doesn't like nil records (crashes).

In my own address book, I have several entries that are just an email - I'm not sure how they got there, but it is certainly possible to have address book entries without a name. Keep this in mind when iterating over the address book.

I use the full name as recommended by Apple. ABRecordCopyCompositeName returns the composite first and last name in the order specified by the user.

Finally, I made it 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 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; } 
+9
source share

First you will need to use the address book structure so that it is added to the Xcode project.

Then you need to split the task into a couple of steps.

1) Get people in the address book

2) Create your CSV file. I assume that you know something about formatting CSV files using characters to separate fields and when to add return characters so that you have a properly formatted file. This is probably left for another question if you need help with this.

3) Save the CSV file somewhere

1) To get an array of all the people in the address book, you will do something like the following. Reference documentation for ABAddressBook here . This will help you access data.

 ABAddressBook *sharedBook = [ABAddressBook sharedAddressBook]; NSArray *peopleList = [sharedBook people]; 

2) You will need to go through each of the people and build your common csv data. Usually you manually create csv data in 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 dataset. If so, then you probably want some code to write your csv data to a file in chunks so that you can free up memory when you go. For simplicity, my code just shows that you are creating a complete file and then saving all the work.

 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 the file somewhere

 //This is an example of writing your csv data to a file that will be saved in the application 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 } 
+2
source share

See the Address Book API Import and Export Entries for Persons and Groups

chack is also an example address book example on this blog.

0
source share