How to determine the type of an address in AddressBook FrameWork (iOS 4.2) - iphone

I´ve one big problem... I plan to write an app that deals with the users addressbook and it´s addresses. Everything´s fine - except the fact that I´m not able to determine whether the addesse´s type is "work", "home" or "other".
Does anybody know how to get the label for home, work and other?
Thanks in advance
Boris
This is the function I´m using at the moment:
+ (void)testing {
//Get the addressbook
ABAddressBookRef _addressBookRef = ABAddressBookCreate ();
//Fetch all contacts
NSArray* allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(_addressBookRef);
//Walk the contacts
for (id record in allPeople) {
//Get the contact´s id
NSInteger recordId = ABRecordGetRecordID((ABRecordRef)record);
//Get the contact´s name and company
NSString* recordName = (NSString *)ABRecordCopyCompositeName((ABRecordRef)record);
NSString* recordCompany = (NSString *)ABRecordCopyValue((ABRecordRef)record, kABPersonOrganizationProperty);
//Get the contact´s addresses
CFTypeRef adressesReference = ABRecordCopyValue((ABRecordRef)record, kABPersonAddressProperty);
NSArray *adressesArray = (NSArray *)ABMultiValueCopyArrayOfAllValues(adressesReference);
CFRelease(adressesReference);
NSLog(#"ID: %d", recordId);
NSLog(#"Name: %#", recordName);
NSLog(#"Firma: %#", recordCompany);
for (NSString *adress in adressesArray) {
NSLog(#"Adresse: %#", adress);
}
[adressesArray release];
}
CFRelease(_addressBookRef);
[allPeople release];
NSLog(#"\n");
}
And here´s the log output:
ID: 1
Name: The first user
Firma: (null)
Adresse: {
City = Reutlingen;
Country = Germany;
CountryCode = de;
Street = "some street";
ZIP = 23456;
}
Adresse: {
City = Reutlingen;
Country = Germany;
CountryCode = de;
State = BW;
Street = "Street number 2";
ZIP = 98765;
}
ID: 2
Name: The second contact
Firma: Firma
Adresse: {
Country = "United States";
CountryCode = us;
Street = Test;
}

here is how you get the address book values extracted:
ABMultiValueRef addresses = ABRecordCopyValue(ref, kABPersonAddressProperty);
for (CFIndex j = 0; j<ABMultiValueGetCount(addresses);j++){
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(addresses, j);
CFStringRef typeTmp = ABMultiValueCopyLabelAtIndex(addreses, j);
CFStringRef labeltype = ABAddressBookCopyLocalizedLabel(typeTmp);
NSString *street = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressStreetKey) copy];
NSString *city = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressCityKey) copy];
NSString *state = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressStateKey) copy];
NSString *zip = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressZIPKey) copy];
NSString *country = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressCountryKey) copy];
[street release];
[city release];
[state release];
[zip release];
[country release];
CFRelease(dict);
CFRelease(type);
CFRelease(typeTmp);
}
CFRelease(addresses);
the label type is what you are looking for.
good luck
shani

Related

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

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

Problem when retrieving address, photo from iphone address book

I have a task to develop the application with phone gap. And retrieve in my application.using javascript.
I want first name,last name,address,photo,home page,email,phone no in my application using phone gap. i have done the following code to retrive them. but i am not getting photo and address in my field.
I have done all code to retrieve the contact in native code. and i am sending it to the javascript file by creating the jsstring object of javascript function.
This is my native implement to read address book data.
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
/** Fetch Contact name */
name = (NSString *)ABRecordCopyCompositeName(person);
NSLog(#"name:%#",name);
/** Fetch Mobile number */
ABMultiValueRef *phones = (ABMultiValueRef *) ABRecordCopyValue(person, kABPersonPhoneProperty);
mobile=[[NSString alloc] initWithString:#""];
NSString *mobileLabel = [[NSString alloc] initWithString:#""];
for (CFIndex i=0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString *) ABMultiValueCopyLabelAtIndex(phones, i);
if ([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel]) {
mobile = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
}
else if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneIPhoneLabel]) {
mobile = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
}
}
/** Fetch Email addres */
emailID = [NSString stringWithFormat:#""];
ABMultiValueRef emails = (ABMultiValueRef) ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i < ABMultiValueGetCount(emails); i++) {
[emailID release];
emailID = (NSString *)ABMultiValueCopyValueAtIndex(emails, 0);
NSLog(#"emailid:%#",emailID);
}
/** Fetch Homepage */
ABMultiValueRef homepage = (ABMultiValueRef *) ABRecordCopyValue(person, kABPersonURLProperty);
NSString *homepageLabel = [NSString stringWithFormat:#""];
homepageID = [NSString stringWithFormat:#""];
for(CFIndex i=0; i < ABMultiValueGetCount(homepage);i++)
{
homepageLabel = (NSString *) ABMultiValueCopyLabelAtIndex(homepage, i);
if([homepageLabel isEqualToString:(NSString *)kABPersonHomePageLabel]){
homepageID = (NSString *)ABMultiValueCopyValueAtIndex(homepage, i);
NSLog(#"homepage:%#",homepageID);
}
}
/** Fatch Image */
NSData *imgData = (NSData *)ABPersonCopyImageData(person);
// call the js to fill the all contact infromation
{
NSString* jsString = [[NSString alloc] initWithFormat:#"fillContactInfo('%#','%#','%#','%#','%#');",name ,mobile ,emailID, homepageID, imgData];
NSLog(#"jstring:%#",jsString);
[webView stringByEvaluatingJavaScriptFromString:jsString];
[jsString release];
}
[emailID release];
[mobile release];
[mobileLabel release];
[homepageID release];
[homepageLabel release];
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier{
/*
* Set up an ABMultiValue to hold the address values; copy from address
* book record.
*/
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonAddressProperty);
// Set up an NSArray and copy the values in.
NSArray *theArray = [(id)ABMultiValueCopyArrayOfAllValues(multi) autorelease];
// Figure out which values we want and store the index.
const NSUInteger theIndex = ABMultiValueGetIndexForIdentifier(multi, identifier);
// Set up an NSDictionary to hold the contents of the array.
NSDictionary *theDict = [theArray objectAtIndex:theIndex];
// Set up NSStrings to hold keys and values. First, how many are there?
const NSUInteger theCount = [theDict count];
NSString *keys[theCount];
NSString *values[theCount];
// Get the keys and values from the CFDictionary. Note that because
// we're using the "GetKeysAndValues" function, you don't need to
// release keys or values. It's the "Get Rule" and only applies to
// CoreFoundation objects.
[theDict getObjects:values andKeys:keys];
// Set the address label's text.
addressid = [NSString stringWithFormat:#"%#, %#",
[theDict objectForKey:(NSString *)kABPersonAddressStreetKey],
[theDict objectForKey:(NSString *)kABPersonAddressCityKey]];
// call the js to fill the all contact infromation
{
NSString* jsString = [[NSString alloc] initWithFormat:#"fillContactAddress('%#');",addressid];
NSLog(#"jscript:%#",jsString);
[webView stringByEvaluatingJavaScriptFromString:jsString];
[jsString release];
}
[[self appViewController] dismissModalViewControllerAnimated:YES];
// If they didn't pick an address, return YES here to keep going.
return NO;
}
At this point i am getting the name,address,phone number,email address,home page,photo in NSLog console when i run the application. Following is my javascript function to retrive them:
function fillContactInfo(name,mobile,email,homepage,imgData){
mobile = mobile.replace(" ", "").replace("(", "").replace(")", "").replace("-", "").replace("+", "").replace("-", "").replace("-", "");
user.contactname = name;
user.contactemail = email;
user.contactphone = mobile;
user.contactimage = imgData;
user.contacturl = homepage;
document.getElementById("contactname").value = user.contactname;
document.getElementById("contactemail").value = user.contactemail;
document.getElementById("contactphone").value = user.contactphone;
document.getElementById("contactimage").src = "data:image/png;base64,user.contactimage";
document.getElementById("contacturl").value = user.contacturl;
}
function fillContactAddress(address){
user.address = address;
document.getElementById("contactaddress").value = user.contactaddress;
}
In the above code I have develop to retrive the contact in my application. But when i run the application at that time i only get name, email, phone number, and home page in my view. but i cant get address, and photo in my view.
I also have try to put the name, phone number, email, and home page in the
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier
class method but it is not giving me result.
And I have html image tag to display image of the contact list.
The content of address inside the ABMultiValue is a NSDictionary structure. You can use the following keys to retrieve desired values. The detail is in this official document.
const CFStringRef kABPersonAddressStreetKey;
const CFStringRef kABPersonAddressCityKey;
const CFStringRef kABPersonAddressStateKey;
const CFStringRef kABPersonAddressZIPKey;
const CFStringRef kABPersonAddressCountryKey;
const CFStringRef kABPersonAddressCountryCodeKey;
About image data, I cannot get a clear picture about how it will be processed in javascript. Maybe you need to transfer those binary data with base64 manner.
Edit:
An address example:
ABMultiValueRef aMulti = ABRecordCopyValue(srcRecord, kABPersonAddressProperty);
if (aMulti != nil) {
int aMultiCount = ABMultiValueGetCount(aMulti);
for (int i = 0; i < aMultiCount; ++i) {
NSDictionary *abDict = (NSDictionary *)ABMultiValueCopyValueAtIndex(aMulti, i);
NSString *street = [abDict objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [abDict objectForKey:(NSString *)kABPersonAddressCityKey];
// obtains other properties ....
[abDict release];
}
CFRelease(aMulti);
}

checking whether the number is in phone contacts are not

i want to check whether the given number is in phone book or not programatically .
i am able to display the contact name of the given number if it is exists in phone book but the program crashes when there is no contact with that number in phone book ...
but what i want is to display name if it exists in phone book..... and display the number if if is not in phone book......
and my code is as follows....
NSMutableArray *names = [[NSMutableArray alloc] init];
NSMutableArray *phonenumbers = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSString *name;
for (id person in thePeople)
{
name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSLog(#"!!!!!! name ---> %#",name);
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
int count1=ABMultiValueGetCount(multi);
NSLog(#"%d",count1);
if ([name length]>0 && count1!=0)
{
NSString *beforenumber = (NSString *)ABMultiValueCopyValueAtIndex(multi, 0);
NSLog(#" contacts:%#",beforenumber );
NSString* removed1=[beforenumber stringByReplacingOccurrencesOfString:#"-"withString:#""];
NSString* removed2=[removed1 stringByReplacingOccurrencesOfString:#")"withString:#""];
NSString* removed3=[removed2 stringByReplacingOccurrencesOfString:#" "withString:#""];
NSString* removed4=[removed3 stringByReplacingOccurrencesOfString:#"("withString:#""];
NSString* removed5=[removed4 stringByReplacingOccurrencesOfString:#"+"withString:#""];
[names addObject:name];
[phonenumbers addObject:removed5];
}
}
int barindex = -1;
barindex = [phonenumbers indexOfObject:number];
if(barindex == -1)
return number;
else
return [names objectAtIndex:barindex];
can any one please help me how to do that.............
thank you.......
The code would be improved but I think that is what you need.
Sample Code

Getting iPhone addressbook contents without GUI

I would like to list all phone numbers (or any other field) of people in the addressbook.
I've written the following code:
- (void)addressBookFill{
ABAddressBookRef addressBook = ABAddressBookCreate();
people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
[addressBook release];
}
- (void)printAddressBook{
for(id person in people){
NSLog(#"%#", [person class]);
NSLog(#"\t%#", person );
}
}
When I invoke the printAddressBook method I get this on my console:
2010-07-06 10:34:11.998 app[91420:207] __NSCFType
2010-07-06 10:34:11.999 app[91420:207] <CPRecord: 0x5d56ce0 ABPerson>
And I don't have any idea, how to dereference this ABPerson object, how to get any info from it.
I tried:
firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
but I got some exceptions.
Can anybody tell me how to get some info from these objects?
Read the documentation about the ABPerson class:
http://developer.apple.com/mac/library/documentation/UserExperience/Reference/AddressBook/Classes/ABPerson_Class/Reference/Reference.html
and also the ABRecord class:
http://developer.apple.com/mac/library/documentation/UserExperience/Reference/AddressBook/Classes/ABRecord_Class/Reference/Reference.html#//apple_ref/occ/cl/ABRecord
[ person valueForProperty: #"propName" ]
You can get the available properties with:
[ ABPerson properties ]
[ EDIT ]
On iPhone, you can use the following code to access a value:
NSString * lastName = (NSString *)ABRecordCopyValue( person, kABPersonLastNameProperty );
May be this code will help you for iOS5, please like it
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;peopleCounter < [arrayOfAllPeople count]; peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef) [arrayOfAllPeople objectAtIndex:peopleCounter];
NSString *name = (__bridge_transfer NSString *) ABRecordCopyCompositeName(thisPerson);
NSLog(#"First Name = %#", name);
ABMultiValueRef emails = ABRecordCopyValue(thisPerson, kABPersonEmailProperty);
for (NSUInteger emailCounter = 0; emailCounter < ABMultiValueGetCount(emails); emailCounter++){
/* And then get the email address itself */
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, emailCounter);
NSLog(#"Email : %#",email);
}
}
CFRelease(addressBook);
You want get only those contact who has email on my contact so use this code for iOS5
Please like it if it work
First add AddressBook.framework and #import <AddressBook/AddressBook.h>
- (NSArray*)printAddressBook{
NSMutableArray *mutableData = [NSMutableArray new];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;peopleCounter < [arrayOfAllPeople count]; peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef) [arrayOfAllPeople objectAtIndex:peopleCounter];
NSString *name = (__bridge_transfer NSString *) ABRecordCopyCompositeName(thisPerson);
NSLog(#"First Name = %#", name);
ABMultiValueRef emails = ABRecordCopyValue(thisPerson, kABPersonEmailProperty);
for (NSUInteger emailCounter = 0; emailCounter < ABMultiValueGetCount(emails); emailCounter++){
/* And then get the email address itself */
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, emailCounter);
NSLog(#"Email : %#",email);
NSMutableDictionary *personDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:name,#"name",email,#"email", nil];
[mutableData addObject:personDict];
}
}
CFRelease(addressBook);
return [NSArray arrayWithArray:mutableData];
}

iPhone SDK Accessing Address book company contact

I have been able to use the SDK to access Address Book contacts for people, but whenever I pick a contact who is a company, my app crashes.
does anyone know the property for the company field?
does anyone know the code to make it work?
thanks in advance
It seems your issue is not related to company tag itself. AB fields need to be managed carefully, released when not used and checked for nil all the time, many fields are not set.
In principle, here is example of how I use it. This function loads contacts (those fields interested for my app) and returns array with contacts to the caller. Hope this is helpful. Note how I release not needed refs.
- (NSArray *)loadContacts
{
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray *contacts = [NSMutableArray array];
for (int i = 0 ; i < nPeople ; i++ ) {
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSString *firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *fullName;
if (firstName && lastName) {
fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
if (firstName) {
fullName = [NSString stringWithString:firstName];
} else if (lastName) {
fullName = [NSString stringWithString:lastName];
} else {
continue;
}
}
NSString *email = nil;
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
if (emails) {
NSArray *emailAddresses = [(NSArray *)ABMultiValueCopyArrayOfAllValues(emails) autorelease];
if (emailAddresses && [emailAddresses count] > 0)
email = [emailAddresses objectAtIndex:0];
CFRelease(emails);
}
if (email) {
NSDictionary *contact = [NSDictionary
dictionaryWithObjectsAndKeys:fullName, #"name",
email, #"email", nil];
[contacts addObject:contact];
}
if (firstName)
CFRelease(firstName);
if (lastName)
CFRelease(lastName);
}
CFRelease(allPeople);
CFRelease(addressBook);
return contacts;
}
you need to use kABPersonOrganizationProperty property for get the company name from addressbook