How to get an email using ABPeoplePicker?

2019-02-28 16:24发布

问题:

I'm not finding Apple's documentation very helpful for actually getting data with a people picker, and there doesn't seem to be much other information on the internet :( I assume I need to get the email in this function:

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{

}

What can I put in there to get the email of the selected person?

回答1:

Use

ABMultiValueRef emails = ABRecordCopyValue(record, kABPersonEmailProperty);

After that, you can use the ABMultiValueRefs API method calls to get email address.

EDIT -- This should give you email

CFStringRef emailId = ABMultiValueCopyValueAtIndex(emails, identifier);


回答2:

Kal answer is actually inaccurate - namely because "ABMultiValueCopyValueAtIndex" takes an index not identifier.

Identifier value is static (like enumeration)

  • "Home Email" is always "0"
  • "Work Email" is always "1".

So it will crash when the person selected only have 1 email stored, which is a "Work Email". Since the identifier is "1", but we need index "0".

Luckily we can use following to get the index:

int index = ABMultiValueGetIndexForIdentifier(emails, identifier);

Code:

if (property == kABPersonEmailProperty) {

    ABMultiValueRef emails = ABRecordCopyValue(person, property);

    NSString *count = [NSString stringWithFormat:@"Count: %d Identifier: %d", ABMultiValueGetCount(emails), identifier];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:count delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];

    if(ABMultiValueGetCount(emails) > 0)
    {
        int index = ABMultiValueGetIndexForIdentifier(emails, identifier);
        CFStringRef emailTypeSelected = ABMultiValueCopyLabelAtIndex(emails, index);
        CFStringRef emailTypeSelectedLocalized = ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emails, index));
        CFStringRef emailValueSelected = ABMultiValueCopyValueAtIndex(emails, index);

        self.lblEmailType.text = (NSString *) emailTypeSelected;
        self.lblEmailTypeLocalized.text = (NSString *) emailTypeSelectedLocalized;
        self.lblEmailValue.text = (NSString *) emailValueSelected;
    }

    [ self dismissModalViewControllerAnimated:YES ];
    return NO;
}

return YES;