如何搜索联系人的电话号码?(地址簿)



在我的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?
}

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

例如,查找姓名中包含"Appleseed"的联系人:

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个月前问的…

最新更新