Unable to fetch mobile numbers from Contact List. iOS6 - iphone

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

Related

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

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

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

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

Addressbook leaks

Hello I m getting firstname, lastname and mobile number from below code
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
NSString* name = (NSString *)ABRecordCopyValue(person,
kABPersonFirstNameProperty);
firstNameLabel.text = name;
[name release];
NSString *lastName =(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
lastNameLabel.text = lastName;
[lastName release];
if (property == kABPersonPhoneProperty) {
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
CFRelease(multiPhones);
NSString *phoneNumber = (NSString *) phoneNumberRef;
numberLabel.text = [NSString stringWithFormat:#"%#", phoneNumber];
// [phoneNumber release];
// CFRelease(phoneNumberRef);
}
//CFRelease(multiPhones);
}
}
[self dismissModalViewControllerAnimated:YES];
return NO;
}
And I am getting leaks.. Here is screen shot. Please help me to resolve leaks
Please check the code
if (property == kABPersonPhoneProperty) {
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (NSString *) phoneNumberRef;
numberLabel.text = [NSString stringWithFormat:#"%#", phoneNumber];
// [phoneNumber release];
CFRelease(phoneNumberRef);
}
}
CFRelease(multiPhones);
}

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.