Get iPhone phone number label from Address Book - iphone

So I have a method to get all the contact phone numbers from the address book on the iPhone, but is there a way to get the phone number label? For example you can do this:
And I'd be looking to modify my method to print out the label (such as iPhone/Home/mobile/etc).
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex n = ABAddressBookGetPersonCount(addressBook);
for( int i = 0 ; i < n ; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex(all, i);
NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
NSLog(#"Name %#", firstName);
ABMultiValueRef *phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
NSString *phoneLabel = #""; // ???
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
//CFRelease(phones);
NSString *phoneNumber = (NSString *)phoneNumberRef;
CFRelease(phoneNumberRef);
NSLog(#" - %# (%#)", phoneNumber, phoneLabel);
[phoneNumber release];
}
}

Simply use -
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
//CFRelease(phones);
NSString *phoneNumber = (NSString *)phoneNumberRef;
CFRelease(phoneNumberRef);
CFRelease(locLabel);
NSLog(#" - %# (%#)", phoneNumber, phoneLabel);
[phoneNumber release];
}
EDIT
Please see the notes for this answer about CFBridgingRelease and __bridge_transfer.

//get the particular contact or email from phone book
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)picker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
// Name of contact.
NSString* name = (NSString *)ABRecordCopyCompositeName(person);
// Numbers of selected contact
ABMutableMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSMutableString *mobile = [[NSMutableString alloc] init];
NSMutableString *office = [[NSMutableString alloc] init];
// Getting if Mobile, Office(work) numbers exist
for(CFIndex numberIndex = 0; numberIndex < ABMultiValueGetCount(phones); numberIndex++)
{
// Number in contact details of current index
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, numberIndex);
// Label of Phone Number
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(phones, numberIndex);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
// Phone number
NSString *phoneNumber = (NSString *)phoneNumberRef;
// Release Phone Number and locationLabel reference object
CFRelease(phoneNumberRef);
CFRelease(locLabel);
NSLog(#" - %# (%#)", phoneNumber, phoneLabel);
if ([phoneLabel isEqualToString:NSLocalizedString(#"mobile", nil)])// Mobile number saving.
{
[mobile appendFormat:#"%#", phoneNumber];
}
else if ([phoneLabel isEqualToString:NSLocalizedString(#"work", nil)])// Office number saving.
{
[office appendFormat:#"%#", phoneNumber];
}
[phoneNumber release];
}
CFRelease(phones);
// Emails of selected contact
ABMutableMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSMutableString *generalMail = [[NSMutableString alloc] init];
NSMutableString *officeMail = [[NSMutableString alloc] init];
// Getting if Home, Office(work) mails exist
for(CFIndex numberIndex = 0; numberIndex < ABMultiValueGetCount(emails); numberIndex++)
{
// Mail in contact details of current index
CFStringRef mailRef = ABMultiValueCopyValueAtIndex(emails, numberIndex);
// Label of Phone Number
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(emails, numberIndex);
NSString *mailLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
// Phone number
NSString *mail = (NSString *)mailRef;
// Release Phone Number and locationLabel reference object
CFRelease(mailRef);
CFRelease(locLabel);
NSLog(#" - %# (%#)", mail, mailLabel);
if ([mailLabel isEqualToString:NSLocalizedString(#"mobile", nil)])// Home mail.
{
[generalMail appendFormat:#"%#", mail];
}
else if ([mailLabel isEqualToString:NSLocalizedString(#"work", nil)])// Office(Work) mail.
{
[officeMail appendFormat:#"%#", mail];
}
[mail release];
}
CFRelease(emails);
[mobile release];
[office release];
[generalMail release];
[officeMail release];
[self dismissViewControllerAnimated:YES completion:nil];
return NO;
}

If you are adding records to the AddressBook, these predefined constants may be what you want, kABPersonPhoneMobileLabel, kABPersonPhoneIPhoneLabel, which are defined in the file ABPerson.h.

the following should help:
NSArray* AccountEmailAddresses(void)
{
NSMutableArray *emailAddresses = [NSMutableArray array];
#try
{
Class MailComposeController = NSClassFromString(#"MailComposeController") ?: NSClassFromString(#"MFMailComposeController");
NSArray *accountEmailAddresses = [MailComposeController performSelector:#selector(accountEmailAddresses)];
for (id address in accountEmailAddresses)
{
if ([address isKindOfClass:[NSString class]])
[emailAddresses addObject:address];
}
}
#catch (NSException *e) {}
return [NSArray arrayWithArray:emailAddresses];
}
ABRecordRef ABGetMe(ABAddressBookRef addressBook)
{
ABRecordRef me = NULL;
NSArray *accountEmailAddresses = AccountEmailAddresses();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex peopleCount = CFArrayGetCount(people);
for (CFIndex i = 0; i < peopleCount; i++)
{
ABRecordRef record = CFArrayGetValueAtIndex(people, i);
ABMultiValueRef emails = ABRecordCopyValue(record, kABPersonEmailProperty);
if (emails)
{
CFIndex emailCount = ABMultiValueGetCount(emails);
for (CFIndex j = 0; j < emailCount; j++)
{
CFStringRef email = ABMultiValueCopyValueAtIndex(emails, j);
if (email)
{
if ([accountEmailAddresses containsObject:(id)email])
me = record;
CFRelease(email);
}
if (me)
break;
}
CFRelease(emails);
}
if (me)
break;
}
return me;
}

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.

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]];

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

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

Memory issues when using ABRecordCopyCompositeName

I have the following piece of code in displaying the mapview.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MKCoordinateRegion region = mapView.region;
MKCoordinateSpan span;
span.latitudeDelta=100;
span.longitudeDelta=100;
NSString *compositeName =(NSString*)ABRecordCopyCompositeName(person);
if([compositeName length] < 1){
firstName = #"No Name";
lastName = #"";
}
else if([firstName length] < 1 && [lastName length] < 1){
firstName = compositeName;
lastName = #"";
}
else if([firstName length] < 1)
{
firstName = lastName;
lastName = #"";
}
addAnnotation = [[[MyAnnotation alloc] initWithCoordinate:mapCenter title:firstName SubTitle:lastName ]autorelease];
[mapView addAnnotation:addAnnotation];
region.span=span;
region.center=mapCenter;
[pool release];
When analysing the project to check for memory leaks, I get the warning, "Potential leak of an object stored into compositeName". Should I release compositeName of type string.
Here object allocated and stored into 'compositeName' has a retain count of +1. I think you just need to release compositeName in this case.
This is Answer similar to my answer
please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
}
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}

How to get all phone numbers with labels for all contacts in address book?

I want to get all the phone numbers with diff labels like "iPhone", "home phone", "mobile number", "other numbers" , etc. for a contact stored in iPhone address book.
How do I get it?
Please help.
Thanks in advance.
I am trying: which is crashing
ABAddressBookRef ab=ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(ab);
NSMutableArray *allNumbers = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(people)];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
ABMultiValueRef numbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(numbers); j++) {
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(numbers, i);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(numbers, j);
CFStringRef locLabel1 = ABMultiValueCopyLabelAtIndex(numbers, j);
NSString *phoneLabel1 =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
NSLog(#" ####### phone no -> %# , phone label -> %# #######)", locLabel1, phoneLabel1);
//CFRelease(phones);
NSString *phoneNumber = (NSString *)phoneNumberRef;
CFRelease(phoneNumberRef);
CFRelease(locLabel);
NSLog(#"phone no -> %# , phone label -> %#)", phoneNumber, phoneLabel);
[phoneNumber release];
}
CFRelease(numbers);
}
CFRelease(people);
Try:
ABMultiValueRef *phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
NSString *phoneNumber = (NSString *)phoneNumberRef;
CFRelease(phoneNumberRef);
CFRelease(locLabel);
NSLog(#" - %# (%#)", phoneNumber, phoneLabel);
[phoneNumber release];
}
This is solid for ARC 64bit iOS8:
- (NSArray *)phoneNumbersOfContactAsStrings:(ABRecordRef)contactRef {
NSMutableArray *mobilePhones = [NSMutableArray arrayWithCapacity:0];
ABMultiValueRef phones = ABRecordCopyValue(contactRef, kABPersonPhoneProperty);
NSArray *allPhoneNumbers = (NSArray *)CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(phones));
for (NSUInteger i=0; i < [allPhoneNumbers count]; i++) {
if ([(NSString *)CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, (long)i)) isEqualToString:(NSString *)kABPersonPhoneMobileLabel]) {
[mobilePhones addObject:CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, (long)i))];
}
if ([(NSString *)CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, (long)i)) isEqualToString:(NSString *)kABPersonPhoneIPhoneLabel]) {
[mobilePhones addObject:CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, (long)i))];
}
}
CFRelease(phones);
return mobilePhones;
}
Solved it this way:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex n = ABAddressBookGetPersonCount(addressBook);
for( int i = 0 ; i < n ; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex(all, i);
NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
NSLog(#"Name %#", firstName);
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef locLabel1 = ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneLabel1 =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel1);
NSLog(#" ### %# --- %# ### )", locLabel1, phoneLabel1);
}
}
Also to get phone number with particular record id, do this:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook);
ABRecordRef ref = CFArrayGetValueAtIndex(all, indexPath.row);
NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
NSLog(#"Name %#", firstName);
NSInteger myID = ABRecordGetRecordID(ref);
NSLog(#"Record id is > %d", myID);
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook,myID);
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
NSString* num = (NSString*)ABMultiValueCopyValueAtIndex(phones, j);
CFStringRef locLabel1 = ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneLabel1 =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel1);
NSLog(#"%# --- %# )", num, phoneLabel1);
}