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

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

Related

How to give permission to access phone Addressbook in ios 10.0?

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.
I added to the .plist NSContactsUsageDescription
doesn't work - device version:10.0
KTSContactsManager *addressBookManager = [KTSContactsManager sharedManager];
addressBookManager.delegate = self;
addressBookManager.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"firstName" ascending:YES]];
if ([isAddressBookTaken isEqualToString:#"false"]) {
[addressBookManager importContacts:^(NSArray *contacts) {
[EBLogger logWithTag:#"TBLContactManager" withBody:#"importContacts"];
DLPhoneBook *phoneBook = [DLPhoneBook new];
NSMutableArray *mutableArray = [NSMutableArray new];
for (int i = 0; i < contacts.count; ++i) {
NSDictionary *record = [contacts objectAtIndex:i];
NSError *err = nil;
DLContactRecord *contactRecord = [[DLContactRecord alloc] initWithDictionary:record error:&err];
NSLog(#" %# %# %# '",contactRecord.firstName, contactRecord.lastName, contactRecord.id);
}
}
You have to add information list in your plist,
Here is information plist for various privacy.
Add Privacy that you want in you plist and check again.
and ADD this code in your file,
- (void)viewDidLoad {
[super viewDidLoad];
contactList=[[NSMutableArray alloc] init];
ABAddressBookRef m_addressbook = ABAddressBookCreate();
if (!m_addressbook) {
NSLog(#"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);
for (int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
//For username and surname
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
[dOfPerson setObject:[NSString stringWithFormat:#"%# %#", firstName, lastName] forKey:#"name"];
//For Email ids
ABMutableMultiValueRef eMail = ABRecordCopyValue(ref, kABPersonEmailProperty);
if(ABMultiValueGetCount(eMail) > 0) {
[dOfPerson setObject:(NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:#"email"];
}
//For Phone number
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:#"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:#"Phone"];
break ;
}
[contactList addObject:dOfPerson];
CFRelease(ref);
CFRelease(firstName);
CFRelease(lastName);
}
NSLog(#"array is %#",contactList);
}
}
For more about it visit,
http://sugartin.info/2011/09/07/get-information-from-iphone-address-book-in-contacts/
Hope it will help you.

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;

Retrieve Phone number by using kABPersonPhoneProperty

I am not able to retrieve mobile number from below code, i am trying lots of thing but unable to solve it. please help me
//this below code is for saving mobile number and phone number
ABRecordRef newPerson = ABPersonCreate();
ABMultiValueAddValueAndLabel(phone, (__bridge CFTypeRef)(txtMob2.text), kABHomeLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, phone, &error);
//image
NSData *dataref = UIImagePNGRepresentation(imgProfile.image);
ABPersonSetImageData(newPerson, (__bridge CFDataRef)(dataref), &error);
ABAddressBookAddRecord(addressbook, newPerson, &error);
ABAddressBookSave(addressbook, nil);
CFRelease(newPerson);
// Now Below code is of displaying details.
- (void)displayContacts
{
int i;
appDelegate.arr_contact = [[NSMutableArray alloc] init];
ABAddressBookRef contactBook =ABAddressBookCreateWithOptions(nil, NULL);
NSArray *allData = (__bridge_transfer NSArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook));
NSUInteger contactNum = 0;
NSInteger recordId;
ABRecordRef recId;
for (i =0; i < [allData count]; i++)
{
appDelegate.dict_contact =[[NSMutableDictionary alloc] init];
ABRecordRef ref =(__bridge ABRecordRef)(allData[i]);
//mobile no and phone no
ABMultiValueRef mobNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFIndex PhoneCount = ABMultiValueGetCount(mobNum);
for (int k = 0; k <PhoneCount; k++) {
strMobile = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(mobNum, k));
strPhone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(mobNum, k));
if ([strMobile isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobileno = (__bridge NSString*)ABMultiValueCopyValueAtIndex(mobNum, k);
}
else if ([strPhone isEqualToString:(NSString *)kABHomeLabel])
{
phoneno = (__bridge NSString*)ABMultiValueCopyValueAtIndex(mobNum, k);
break;
}
NSLog(#"Mobile: %# phone: %#, %#",mobileno, phoneno, strPhone);
[appDelegate.dict_contact setObject:[NSString stringWithFormat:#"%#",mobileno] forKey:#"mobno"];
[appDelegate.dict_contact setObject:[NSString stringWithFormat:#"%#",phoneno] forKey:#"phnno"];
}
//image
NSData *imgData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(ref, kABPersonImageFormatThumbnail);
UIImage *image;
if (imgData)
{
image = [UIImage imageWithData:imgData];
NSLog(#"add image: %#",image);
}else
{
image = [UIImage imageNamed:#"dummy.png"];
}
[appDelegate.dict_contact setObject:image forKey:#"image"];
[appDelegate.arr_contact addObject:appDelegate.dict_contact];
}
}
Please check my edited code.
Please See this code....
-(void)GetAddressBook
{
Contacts = [[NSMutableArray alloc]init];
if (ABAddressBookCreateWithOptions) {
#try {
ABAddressBookRef addressBook = ABAddressBookCreate();
// NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
if (!addressBook) {
NSLog(#"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSLog(#"opening address book ==%ld",nPeople);
for (int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
NSString *Contact;
ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));
CFStringRef firstName, lastName;
NSMutableArray *array = [[NSMutableArray alloc]init];
NSString *email;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
ABMultiValueRef multiValueRef = ABRecordCopyValue(ref, kABPersonEmailProperty);
array = [(__bridge NSMutableArray *)ABMultiValueCopyArrayOfAllValues(multiValueRef) mutableCopy];
email = ([array count] > 0) ? array[0] : #"";
if(firstName)
{
Contact = [NSString stringWithFormat:#"%#", firstName];
if(lastName)
Contact = [NSString stringWithFormat:#"%# %#",firstName,lastName];
}
[dOfPerson setObject:Contact forKey:#"name"];
[dOfPerson setObject:[NSString stringWithFormat:#"%d", i] forKey:#"id"];
[dOfPerson setObject:[NSString stringWithFormat:#"%#",#""] forKey:#"found"];
[dOfPerson setObject:email forKey:#"email"];
NSString* mobileLabel;
for(CFIndex j = 0; j< ABMultiValueGetCount(phones); j++)
{
mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
break ;
}
}
[Contacts addObject:dOfPerson];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
dispatch_async(dispatch_get_main_queue(), ^{
});
Here you will get Phone number, First Name, Last name and Email Id. Here Contacts is an NSMutableArray. Also view this answer for a complete set of code.
contact details from ipad using objective-c
Try This In this code I'm getting both the name and mobile number if you want the mobile number only use this kABPersonPhoneProperty:
CFErrorRef * error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for (int i=0;i < nPeople;i++)
{
NSString* name;
NSMutableDictionary* tempContactDic = [NSMutableDictionary new];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
CFStringRef firstName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
name = (__bridge NSString *)(firstName);
[tempContactDic setValue:name forKey:#"name"];
//fetch email id
NSString *strEmail;
NSMutableString* strMobile;
ABMultiValueRef email = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFStringRef tempEmailref = ABMultiValueCopyValueAtIndex(email, 0);
strEmail = (__bridge NSString *)tempEmailref;
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"-" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"(" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#")" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#" " withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"+" withString:#""];
strMobile = [[NSMutableString alloc] initWithString:strEmail];
if ([strEmail length] == 10) {
[strMobile insertString:#"91" atIndex:0];
}
else {
}
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:strMobile];
[tempContactDic setValue:myNumber forKey:#"phone"];
[contactsArray addObject:tempContactDic];
}
/// With below two steps of code you'll get the contacts in alphabetical order
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[contactsArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

I fetch contact in addressbook iphone 4s not working

+(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;
}

iPhone - address book search crash

Some of our app store users are reporting a crash while searching their address book.
I'm pretty lost here cause I can't reproduce this issue.
Is there anything wrong with how I'm querying the address book ? Thanks!!
+ (NSDictionary *) scanAddressBook
{
#if TARGET_OS_IPHONE
NSUInteger i;
CFIndex index;
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
if ( people==nil || (people && ([people count] == 0)))
{
TRACE_LOG(#"scanAddressBook ", #"NO ADDRESS BOOK ENTRIES TO SCAN");
if(people) [people release];
CFRelease(addressBook);
return nil;
}
NSMutableArray *numbersArray = [NSMutableArray new];
NSMutableArray *mailsArray = [NSMutableArray new];
for ( i=0; i<[people count]; i++ )
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
NSMutableDictionary *phoneDictionary = [NSMutableDictionary new];
CFStringRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString* log =[NSString stringWithFormat:#"-----CONTACT ENTRY -> %# : %#", firstName, lastName ];
TRACE_LOG(#"scanAddressBook",log);
NSString *userName = #"NoName";
if (firstName && lastName)
userName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
else if (firstName)
userName = [NSString stringWithFormat:#"%#", firstName];
else if (lastName)
userName = [NSString stringWithFormat:#"%#", lastName];
if(firstName) CFRelease(firstName);
if(lastName) CFRelease(lastName);
//
// Phone Numbers
//
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );
for ( index=0; index<phoneNumberCount; index++ )
{
CFStringRef phoneNumberLabel = ABMultiValueCopyLabelAtIndex( phoneNumbers, index);
CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex( phoneNumbers, index);
CFStringRef phoneNumberLocalizedLabel = ABAddressBookCopyLocalizedLabel( phoneNumberLabel );
// converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
// Find the ones you want here
//
NSString* log =[NSString stringWithFormat:#"-----PHONE ENTRY -> %# : %#", phoneNumberLocalizedLabel, phoneNumberValue ];
TRACE_LOG(#"scanAddressBook",log);
if (![NetworkingUtils validatePhoneNumber:(NSString *)phoneNumberValue]) {
NSLog(#"invalid phone number: %#",phoneNumberValue);
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
continue;
}
[phoneDictionary setObject:(NSString *)phoneNumberValue forKey:InviteUserDataNumberKeyID];
[phoneDictionary setObject:(NSString *)phoneNumberLocalizedLabel forKey:InviteUserDataNumberTypeKeyID];
[phoneDictionary setObject:(NSString *)userName forKey:InviteUserDataNameTypeKeyID];
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
NSMutableDictionary *copyPhoneDict = [phoneDictionary copy];
[numbersArray addObject:copyPhoneDict];
[copyPhoneDict release];
}
CFRelease(phoneNumbers);
[phoneDictionary release];
NSMutableDictionary *mailDictionary = [NSMutableDictionary new];
ABMutableMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex mailsNumberCount = ABMultiValueGetCount( emails );
for ( index=0; index < mailsNumberCount; index++ )
{
CFStringRef emailValue = ABMultiValueCopyValueAtIndex( emails,index);
// converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
// Find the ones you want here
//
NSString* log =[NSString stringWithFormat:#"-----EMAIL ENTRY -> : %#", emailValue ];
TRACE_LOG(#"scanAddressBook",log);
if (![NetworkingUtils validateEmail:(NSString *)emailValue]) {
NSLog(#"invalid email address: %#",(NSString *)emailValue);
if (emailValue) {
CFRelease(emailValue);
}
continue;
}
[mailDictionary setObject:(NSString *)emailValue forKey:InviteUserDataMailKeyID];
[mailDictionary setObject:(NSString *)#"email" forKey:InviteUserDataMailTypeKeyID];
[mailDictionary setObject:(NSString *)userName forKey:InviteUserDataMailOwnerKeyID];
if (emailValue) {
CFRelease(emailValue);
}
NSMutableDictionary *copyMailDict = [mailDictionary copy];
[mailsArray addObject:copyMailDict];
[copyMailDict release];
}
if(emails) CFRelease(emails);
[mailDictionary release];
[pool drain];
}
NSString *countryCode = [[NSUserDefaults standardUserDefaults] objectForKey:RequestUserCountryCodeKeyID];
if (!countryCode) {
NSLocale *locale = [NSLocale currentLocale];
NSString *aCode = [locale objectForKey: NSLocaleCountryCode];
countryCode = [[NetworkingUtils codesByCountryCode] objectForKey:aCode];
}
NSDictionary *aDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [[numbersArray copy] autorelease], InviteUsersNumbersArrayKeyID,
[[mailsArray copy] autorelease], InviteUsersMailsArrayKeyID,
countryCode, RequestUserCountryCodeKeyID, nil];
[numbersArray release];
[mailsArray release];
[people release];
CFRelease(addressBook);
return aDictionary;
#else
return nil ;
#endif
}
CFRelease() will crash if you provide a NULL value. I see most of your CFRelease() calls do check for NULL, but not all of them.
Most likely one of these is triggering the crash?
I'm not very familiar with ABAddressBook, so don't know in what situations they would return NULL.
On a related note, Objective-C's -release method does not crash on nil, so you may as well change: if(people) [people release]; to just [people release]; as all methods in Objective-C will silently do nothing if sent to a nil.