如何仅通过地址簿中的电子邮件地址访问联系人?

时间:2012-08-15 00:37:04

标签: iphone ios email contacts addressbook

我正在访问所有用户联系人并通过应用程序向他们发送电子邮件。如果他们有电子邮件地址,我可以很好地访问所有联系人。如果他们没有电子邮件地址,那么它会给我一个错误,我试图在我尝试将地址添加到地址列表之前检查他们是否有电子邮件地址。我正在使用此代码。它在if语句的行上给出了一个错误:if((ABMultiValueCopyValueAtIndex(email,0)!= NULL))

如何只访问拥有电子邮件地址的联系人?

NSMutableArray* contactsArray = [NSMutableArray new];
ABAddressBookRef m_addressbook = ABAddressBookCreate();


CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);
for (int i=0;i < nPeople;i++)
{
    NSMutableDictionary* tempContactDic = [NSMutableDictionary new];
    ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
    CFStringRef firstName, lastName;
    firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
    lastName  = ABRecordCopyValue(ref, kABPersonLastNameProperty);
    NSString *name = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
    [tempContactDic setValue:name forKey:@"name"];


    //fetch email id
    NSString *strEmail;
    ABMultiValueRef email = ABRecordCopyValue(ref, kABPersonEmailProperty);

    if ((ABMultiValueCopyValueAtIndex(email, 0) != NULL))
    {

    CFStringRef tempEmailref = ABMultiValueCopyValueAtIndex(email, 0);
    strEmail = (__bridge  NSString *)tempEmailref;

    [contactsArray addObject:strEmail];
    }
}

2 个答案:

答案 0 :(得分:1)

错误是因为您尝试通过复制数组中的第一项来检查是否有可用的电子邮件地址,并检查该值是否为NULL。但如果数组为空,则无法从中复制任何项目。

您应该做的是检查数组是否包含任何项目:

if (ABMultiValueGetCount(email) > 0) {
    // There is at least one item in the email array/

}

另请注意,如果您为该联系人设置了超过1封电子邮件,则您的代码只会复制该联系人的第一个电子邮件地址。

答案 1 :(得分:1)

您可以使用此代码从联系人中获取所有用户的所有电子邮件。

- (void) getEmailsOfAllContacts
{
    ABAddressBookRef _addressBookRef = ABAddressBookCreate();
    NSArray * allPeople = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(_addressBookRef);

    for (id record in allPeople)
    {        
        CFTypeRef emailProperty = ABRecordCopyValue((__bridge ABRecordRef)record, kABPersonEmailProperty);

        NSArray * allEmailArray = ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty));

        NSString * email;

        for (int i = 0; i < [allEmailArray count]; i++)
        {
            email = [allEmailArray objectAtIndex: i];
            if (isEmpty(email) == NO)
            {
                [_allContactsEmailArray addObject: email];
            }
        }
    }

    CFRelease(_addressBookRef);
    allPeople = nil;
}