Find a "work" email address for a person in iPhone Address Book?
Asked Answered
C

1

5

Is there a way to find a particular kind of email address for a person from the iPhone Address Book? I know how to get all of the email addresses for a person, just not how to identify what kind of e-mail address it is ("home", "work", etc.)...nor (and this might be preferable), a way to directly access that address without having to iterate through them all.

Thanks.

Carlycarlye answered 22/1, 2010 at 19:57 Comment(0)
F
15

Check for a label of kABWorkLabel using ABMultiValueCopyLabelAtIndex.

For example, if you have an ABRecordRef named "person", this code will set a single NSString named "emailAddress":

// Email address (if only one, use it; otherwise, use the first work email address)
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1) {
    value = ABMultiValueCopyValueAtIndex(multi, 0);
    emailAddress = (NSString*)value;
    [emailAddress retain];
    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 (label && CFStringCompare(label, kABWorkLabel, 0) == 0) {
            emailAddress = (NSString*)value;
            [emailAddress retain];
            break;
        }

        CFRelease(label);
        CFRelease(value);
    }
}
CFRelease(multi);
Fiorin answered 22/1, 2010 at 20:34 Comment(4)
Just to condense the response, the secret here is the kABWorkLabel which gets out a work address. Note that your code has a potential leak issue though, as there could be a number of work email addresses so emailAddress should either be released before setting, or you need to break out of the loop, or (better) you need to spit out an array of work email addresses.Laudable
Good points. I took this from my app and I was actually setting a property (no leak) and I only care about geting one.Fiorin
the above code fails if more than one email address is set but no work label is assigned. it also fails if more than one address is set but labels are missing since CFStringCompare will crash. Nevertheless thanks for posting this!Wines
@MartinReichl I think I fixed the crash by adding a check for label before using it. What is the first issue you found? Just that it doesn't find an email or is there a bug?Fiorin

© 2022 - 2024 — McMap. All rights reserved.