Import AddressBook Contact Info, how to handle empty fields? - iphone

I am importing contacts info into some textfields, but the app crashes if there are no entries for certain fields, like phone, email, etc.
Here are my textfields:
First Name
Middle Name
Last Name
Main Phone
Mobile Phone
Email Address
Website
Suppose the selected contact doesnt have a second Phone number (in this case: Mobile Phone) or there are no URL entries for the contact. The app crashes.
*ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSMutableArray *phones = [[NSMutableArray alloc] init];
int i;
for (i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
NSString *aPhone = [(NSString*)ABMultiValueCopyValueAtIndex(phoneMulti, i) autorelease];
[phones addObject:aPhone];
}
accountPhone1TextField.text = [phones objectAtIndex:0];
accountPhone2TextField.text = [phones objectAtIndex:1];
CFRelease(phoneMulti);
[phones release];*
Or if I am trying to get an email address from the contact and it doesnt exist this will crash:
NSString *anEmail = [(NSString*)ABMultiValueCopyValueAtIndex(emailMulti, i) autorelease];
//Variable is not a CFString
***** UPDATE *****
Ended up using the following code:
ABMutableMultiValueRef emailMulti = ABRecordCopyValue(person, kABPersonEmailProperty);
NSMutableDictionary *myEmailDict = [NSMutableDictionary dictionaryWithCapacity:ABMultiValueGetCount(emailMulti)];
for (CFIndex i = 0; i < ABMultiValueGetCount(emailMulti); i++) {
emailLabel = ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emailMulti, i));
email = ABMultiValueCopyValueAtIndex(emailMulti, i);
[myEmailDict setObject:(NSString*)email forKey:(NSString*)emailLabel];
CFRelease(email);
CFRelease(emailLabel);
}

if (phones.count > 0) {
accountPhone1TextField.text = [phones objectAtIndex:0];
}
if (phones.count > 1) {
accountPhone2TextField.text = [phones objectAtIndex:1];
}

Related

fetching only mobile section record (not from iphone, home label etc) from addressbook?

How do I fetch only mobile section record from addressbook in ios?
I want to add only one record to my array that is fetched from mobile section record.
How do I do that. I am getting all the phone property records. but I need to get only mobile section record.
NSArray *allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
NSLog(#"allpeople%#", allPeople);
for (id record in allPeople) {
CFTypeRef phoneProperty = ABRecordCopyValue((ABRecordRef)record, kABPersonPhoneProperty);
NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
NSLog(#"phones %#",phones);
CFRelease(phoneProperty);
NSMutableDictionary *newRecord = [[NSMutableDictionary alloc] init];
NSMutableString *newPhone = [[NSMutableString alloc] init];
for (NSString *phone in phones) {
if(![newPhone isEqualToString:#""])
[newPhone appendString:#", "];
[newPhone appendString:phone];
}
You can try something like this..
ABMultiValueRef phoneNumbers = ABRecordCopyValue(abPerson, kABPersonPhoneProperty);
if (phoneNumbers) {
CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
NSString *phone = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
CFStringRef label = ABMultiValueCopyLabelAtIndex(phoneNumbers, i);
if (label) {
if (CFEqual(label, kABPersonPhoneMobileLabel)) {
primaryPhoneText.text = phone;
} else {
}
CFRelease(label);
[allPhones addObject:phone]; // allPhones is an array here.
}
}
CFRelease(phoneNumbers);
}
Hope this will help you out..
Enjoy coding..

How to access contacts only with email address in address book?

I am accessing all of the users contacts and emailing them through the app. I can access all of the contacts fine, if they have an email address. If they don't have an email address, then it gives me an error, I am trying to check if they have an email address before I attempt to add the address to the list of addresses. I am using this code. It gives me an error on the line of the if statement here: if ((ABMultiValueCopyValueAtIndex(email, 0) != NULL))
How can I access only the contacts who have email addresses?
NSMutableArray* contactsArray = [NSMutableArray new];
ABAddressBookRef m_addressbook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);
for (int i=0;i < nPeople;i++)
{
NSMutableDictionary* tempContactDic = [NSMutableDictionary new];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
NSString *name = [NSString stringWithFormat:#"%# %#", firstName, lastName];
[tempContactDic setValue:name forKey:#"name"];
//fetch email id
NSString *strEmail;
ABMultiValueRef email = ABRecordCopyValue(ref, kABPersonEmailProperty);
if ((ABMultiValueCopyValueAtIndex(email, 0) != NULL))
{
CFStringRef tempEmailref = ABMultiValueCopyValueAtIndex(email, 0);
strEmail = (__bridge NSString *)tempEmailref;
[contactsArray addObject:strEmail];
}
}
The error is because you are trying to check whether there are email address available by copying the first item in the array and check if the value is NULL. But if the array is empty you can't copy any items from it.
What you should do is check if the array holds any items:
if (ABMultiValueGetCount(email) > 0) {
// There is at least one item in the email array/
}
Also be aware they your code only copies the first e-mail address for the contact, if more then 1 e-mail is set for that contact you might want to loop thru the e-mail array.
U can use this code to fetch all emails of all users from your contacts.
- (void) getEmailsOfAllContacts
{
ABAddressBookRef _addressBookRef = ABAddressBookCreate();
NSArray * allPeople = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(_addressBookRef);
for (id record in allPeople)
{
CFTypeRef emailProperty = ABRecordCopyValue((__bridge ABRecordRef)record, kABPersonEmailProperty);
NSArray * allEmailArray = ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty));
NSString * email;
for (int i = 0; i < [allEmailArray count]; i++)
{
email = [allEmailArray objectAtIndex: i];
if (isEmpty(email) == NO)
{
[_allContactsEmailArray addObject: email];
}
}
}
CFRelease(_addressBookRef);
allPeople = nil;
}

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

iPhone address book problem

I'm having a bit of an issue with using the address book to get the names of the contacts from the device into my own contacts view within my application.
The code I have works fine on the emulator but I when tested on an iPhone 4 it will crash, the application seems to work fine if there are two or less contacts but 3 or more and the application crashes.
Here is the code I am using to get the names of contacts into an array.
ABAddressBookRef addressBook;
bool wantToSaveChanges = YES;
bool didSave;
CFErrorRef error = NULL;
addressBook = ABAddressBookCreate();
listOfContacts = [[NSMutableArray alloc]init];
int i;
int len = (int) ABAddressBookGetPersonCount(addressBook);
for(i = 1; i< (len+1); i++){
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, (ABRecordID) i);
NSString* name = (NSString *)ABRecordCopyCompositeName(person);
ABMultiValueRef number = (NSString *)ABRecordCopyValue(person,kABPersonPhoneProperty);
NSString *mobileNum = (NSString *)ABMultiValueCopyValueAtIndex(number, 0 );
NSLog(#"Name = %#", name);
NSLog(#"Number = %#", mobileNum);
[listOfContacts addObject:name];
[name release];
[mobileNum release];
}
if(ABAddressBookHasUnsavedChanges(addressBook)){
if(wantToSaveChanges){
didSave = ABAddressBookSave(addressBook, &error);
if(!didSave){
//Error
}
}
else{
ABAddressBookRevert(addressBook);
}
}
When it crashes this is the line that gets highlighted in Xcode:
NSString* name = (NSString *)ABRecordCopyCompositeName(person);
And the error states:
Thread 1: Program received signal: "EXC_BAD_ACCESS"
Can anyone see what the problem might be? I dont understand why it would work on the emulator but not on the device? And also why it works for up to two contacts but not 3 or more??
Just a guess:
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, (ABRecordID) i);
This line looks fishy for me. I doubt that the record IDs are numbered from 1 to whatever. Especially if you have deleted an entry.
This would explain why it works on the simulator, I guess you just added some test contacts and never deleted one.
Here is how I solved it:
(Note how I make sure to call only active records, also I created a customized Contact class)
This code takes care of edge case like: email/phone doesn't exist, or exists more than once...
+(NSArray *)getAddressBook{
ABAddressBookRef addressBook;
bool wantToSaveChanges = YES;
bool didSave;
CFErrorRef error = NULL;
addressBook = ABAddressBookCreate();
NSMutableArray *listOfContacts = [[NSMutableArray alloc]init];
CFArrayRef array=ABAddressBookCopyArrayOfAllPeople(addressBook);
int len=CFArrayGetCount(array);
for (int i = 0; i<len; i++){
ABRecordRef person = CFArrayGetValueAtIndex(array, i);
if (ABRecordGetRecordType(person)==kABPersonType){
NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
ABMultiValueRef emails = (ABMultiValueRef)ABRecordCopyValue(person,kABPersonEmailProperty);
ABMultiValueRef numbers = (ABMultiValueRef)ABRecordCopyValue(person,kABPersonPhoneProperty);
int sumEmails=ABMultiValueGetCount(emails);
int sumNumbers=ABMultiValueGetCount(numbers);
for (int j=0; j<(sumNumbers>sumEmails?sumNumbers:sumEmails); j++) {
ACL_AB_Contact *contact=[[ACL_AB_Contact alloc]initWithFirstName:firstName LastName:lastName];
if (j<sumEmails){
contact.emailAddress=(NSString *)ABMultiValueCopyValueAtIndex(emails,j);
}
if (j<sumNumbers){
contact.phoneNumber=(NSString *)ABMultiValueCopyValueAtIndex(numbers,j);
}
[contact logContact];
[listOfContacts addObject:contact];
[contact release];
}
}
}
if(ABAddressBookHasUnsavedChanges(addressBook)){
if(wantToSaveChanges){
didSave = ABAddressBookSave(addressBook, &error);
if(!didSave){
//Error
}
}
else{
ABAddressBookRevert(addressBook);
}
}
return [listOfContacts autorelease];
}
The record IDs are dynamic. It means that if you add 2 contacts and then remove the first, you will have only a contact with id "2". So I wouln't use a for statement to get through the contacts. Follow the Address Book Programming Guide

How to search the iphone address book for a specific phone number?

I am developing an app that connects to another iphone using bonjour. One of its features is when I connect to the other device it will automatically check if I have the other persons phone number. So my problem is how do I check my address book for the phone number provided by the other device?
Here's an example extracted from one of my address book methods. I wasn't searching by phone number but this gives you an idea have how to move forward with what you need:
- (void) scanAddressBookSample
{
NSUInteger i;
NSUInteger k;
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
if ( people==nil )
{
NSLog(#"NO ADDRESS BOOK ENTRIES TO SCAN");
CFRelease(addressBook);
return;
}
for ( i=0; i<[people count]; i++ )
{
ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
//
// Phone Numbers
//
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );
for ( 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 -> %# : %#", phoneNumberLocalizedLabel, phoneNumberValue );
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
}
}
[people release];
CFRelease(addressBook);
}
-(void)createQuickAccessContacts{
NSMutableDictionary contactDictionary= [[NSMutableDictionary alloc]init];
CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex n = ABAddressBookGetPersonCount(addressBook);
NSDate *date=[NSDate date];
for( int i = 0 ; i < n ; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex(all, i);
ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
NSString *phoneNumber = (__bridge NSString *)phoneNumberRef;
[contactDictionary setObject:(__bridge id)(ref) forKey:phoneNumber];
}
}
NSLog(#" Time taken %f for %i contacts",[[NSDate date] timeIntervalSinceDate:date],[contactDictionary count]);
}
This takes like 0.5 sec for 2.5k contacts to fill
then you can find the contact using number
ABRecordRef ref= [contactDictionary objectForKey:#"89xxxxxxx"];
its super fast takes like 0.000x seconds
Use This. this is my code.
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");
search method. it would be faster than using array
"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;
}