且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从联系人(iOS)获取所有电子邮件地址

更新时间:2023-02-25 10:41:46

是的,你可以做到这一点。你想要这样做似乎很可疑(为什么你需要这些信息?),但这并不困难。

Yes, you can do this. It seems suspicious that you would want to do this (why do you need this information?), but it isn't difficult to do.

你可以使用 ABRecordCopyVal 。代码看起来像这样(未经测试):

You can use ABAddressBookCopyArrayOfAllPeople to get an CFArrayRef with all of the people, and then you can query kABPersonEmailProperty of each using ABRecordCopyValue. The code would look something like this (untested):

ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(people)];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
    ABRecordRef person = CFArrayGetValueAtIndex(people, i);
    ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
    for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++) {
        NSString* email = (NSString*)ABMultiValueCopyValueAtIndex(emails, j);
        [allEmails addObject:email];
        [email release];
    }
    CFRelease(emails);
}
CFRelease(addressBook);
CFRelease(people);

(内存分配可能稍微偏差;自从我开发Cocoa / Core以来已经有一段时间了基础代码。)

(Memory allocation may be a little off; it's been a while since I've developed Cocoa/Core Foundation code.)

但严重的是,问你为什么要这样做。只需使用Apple提供的API在适当的时间提供联系人选择器,就有可能获得更好的解决方案。

But seriously, question why you are doing this. There's a good chance that there's a better solution by just using the Apple-provided APIs to present a contact picker at appropriate times.