0

我正在访问所有用户联系人并通过应用程序向他们发送电子邮件。如果他们有电子邮件地址,我可以访问所有联系人。如果他们没有电子邮件地址,那么它会给我一个错误,我试图在尝试将地址添加到地址列表之前检查他们是否有电子邮件地址。我正在使用此代码。它在这里的 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];
    }
}
4

2 回答 2

1

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

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

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

}

另请注意,您的代码仅复制联系人的第一个电子邮件地址,如果为该联系人设置了超过 1 个电子邮件,您可能希望循环通过电子邮件数组。

于 2012-08-15T08:02:46.947 回答
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;
}
于 2013-04-23T13:25:24.293 回答