Retrieve Phone number by using kABPersonPhoneProperty - iphone

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

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.

code for fetching contacts is not working on iphone 5 but its working fine in iphone 4

I have developed an app which is fetching contacts from iphone its working fine in iphone 4 but it is failed to do the same in iphone 5 .
view did load--------
ABAddressBookRef addressBook = ABAddressBookCreate();
CFErrorRef myError = NULL;
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, &myError);
switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusNotDetermined: {
NSLog(#"kABAuthorizationStatusNotDetermined");
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access.
AddressBookUpdated(addressBookRef, nil, (__bridge void *)(self));
CFRelease(addressBookRef); void insert();
}); }
break;
case kABAuthorizationStatusRestricted:{
NSLog(#"kABAuthorizationStatusRestricted");
}
break;
case kABAuthorizationStatusDenied:
NSLog(#"kABAuthorizationStatusDenied");
break;
case kABAuthorizationStatusAuthorized:{
NSLog(#"kABAuthorizationStatusAuthorized");
AddressBookUpdated(addressBookRef, nil, (__bridge void *)(self));
CFRelease(addressBookRef);
break;
}}
function for fetching contact in this function i am fetching contacts & taking them in an array
void AddressBookUpdated(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) {
#try{
NSString *userDefKey;
NSString *docsDir;
NSArray *dirPaths;
const char *dbpath;
NSString *databasePath;
sqlite3 *contactDB;
sqlite3 *db;
NSString *dbPath1;
NSString *dbPath;
NSMutableArray *data,*number,*email;
data=[[NSMutableArray alloc]init];
number=[[NSMutableArray alloc]init];
email=[[NSMutableArray alloc]init];
ABAddressBookRevert(addressBook);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
ABAddressBookRef addressBook1 = ABAddressBookCreate();
NSArray *people1 = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *emailid;
ABMultiValueRef emailProperty = ABRecordCopyValue(person, kABPersonEmailProperty);
// ABMultiValueRef multi = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
//NSString *eid=(__bridge NSString *)(ABRecordCopyValue(person, kABPersonEmailProperty));
NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
// NSInteger *i=(__bridge NSInteger*)ABRecordCopyValue(person, kABPersonPhoneMobileLabel);
if(emailArray.count==0)
[email addObject:#" "];
else{
emailid=emailArray[0];
if(emailid.length!=0)
[email addObject:emailid];
}
//NSLog(#"email array %#",eid);
if(lastName.length<1)
{
[data addObject:firstName];
}
else
{
NSString *combined = [NSString stringWithFormat: #"%# %#",
firstName, lastName];
[data addObject:combined];
}
}
//NSLog(#"phone count is %d",data.count);
//number = [NSMutableArray arrayWithCapacity:data.count];
//NSLog(#"phone count is %d",number.count);
for(id person in people1){
//fetch multiple phone nos.
ABMultiValueRef multi = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++) {
NSString* phone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, j);
//NSLog(#"phone no is %#",phone);
[number addObject:phone];
}
}
NSLog(#"data is %#",data);
NSLog(#"phone number %#",number);
NSLog(#"email id is %#",email);
}

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;

Unable to fetch mobile numbers from Contact List. iOS6

I am new to iphone App Development(using iOS6) and have been facing problem with fetching the mobile Numbers from the contact List into a UITableViewController. I can get the first name and last name correctly but the phone Numbers are being returned as null. I could not understand the reason behind this.What is it that I am doing wrong? My code is as follows:
NSMutableArray *people = (__bridge_transfer NSMutableArray *) ABAddressBookCopyArrayOfAllPeople (addressBookRef);
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:indexPath.row]), kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:indexPath.row]), kABPersonLastNameProperty);
ABMultiValueRef phoneNumbers = ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:indexPath.row]),kABPersonPhoneProperty);
if (([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil) &&
([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil))
{
// do nothing
}
else
{
aName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
if ([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil)
{
aName = [NSString stringWithFormat:#"%#", lastName];
}
if ([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil)
{
aName = [NSString stringWithFormat:#"%#", firstName];
}
//[self.tableItems addObject:aName];
NSLog(#"%# added",aName);
}
//fetch multiple phone nos. and use only 0th
id person = people[indexPath.row];
ABMultiValueRef multi = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
NSString* phone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, 0);
NSLog(#"%#",phone);
[cell.detailTextLabel setText:phone];
[cell.textLabel setText:aName];
return cell;
Here this is a full working 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(), ^{
});
}
The Phone numbers are to be taken like ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));

Get iPhone phone number label from Address Book

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