如何搜索联系人的电话号码? (Abaddressbook)

时间:2013-04-01 18:32:55

标签: ios objective-c abaddressbook

在我的iOS应用中,我想找到与该名称匹配的联系人的电话号码。

CFErrorRef *error = NULL;

// Create a address book instance.
ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

// Get all people's info of the local contacts.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {

    // Get the person of the ith contact.
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
    ## how do i compare the name with each person object?
}

1 个答案:

答案 0 :(得分:0)

您可以使用ABRecordCopyCompositeName获取此人的姓名,并测试搜索字符串是否包含在CFStringFind的名称中。

例如,要找到&#34; Appleseed&#34;以他的名义:

CFStringRef contactToFind = CFSTR("Appleseed");

CFErrorRef *error = NULL;

// Create a address book instance.
ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

// Get all people's info of the local contacts.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {

    // Get the person of the ith contact.
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

    // Get the composite name of the person
    CFStringRef name = ABRecordCopyCompositeName(person);

    // Test if the name contains the contactToFind string
    CFRange range = CFStringFind(name, contactToFind, kCFCompareCaseInsensitive);

    if (range.location != kCFNotFound)
    {
        // Bingo! You found the contact
        CFStringRef message = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Found: %@"), name);
        CFShow(message);
        CFRelease(message);
    }

    CFRelease(name);
}

CFRelease(allPeople);
CFRelease(addressbook);

希望这会有所帮助。虽然5个月前就提出了你的问题......