通过 phone、电子邮件、姓名在地址簿中找到 ios ABRecordRef 联系人

find ios ABRecordRef contact in AddressBook by phone, email, name

我需要在 AdreesBook 中找到联系人才能添加新的社交网络。 有时我必须通过电话和电子邮件或电话、名字和姓氏来查找联系人,是否有任何类型的查询来获取 ABRecordRef 联系人而不是等待?

我的许多用户有超过 1000 个联系人,我需要更新其中的很多,所以如果我唯一的解决方案是做那么多时间,效率不高...

有什么想法吗??

谢谢!

以下方法可以帮助您使用 phone 号码 获取联系方式。为此,它使用了 kABPersonPhoneProperty,同样你可以编写另一个函数来搜索 emailname:

  • 对于电子邮件,使用属性:kABPersonEmailProperty
  • 名字kABPersonFirstNameProperty

更多详情,请浏览:ABPerson Reference

希望对您有所帮助。

#import <AddressBook/AddressBook.h>

-(NSArray *)contactsContainingPhoneNumber:(NSString *)phoneNumber {
    /*
     Returns an array of contacts that contain the phone number
     */

    // Remove non numeric characters from the phone number
    phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""];

    // Create a new address book object with data from the Address Book database
    CFErrorRef error = nil;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    if (!addressBook) {
        return [NSArray array];
    } else if (error) {
        CFRelease(addressBook);
        return [NSArray array];
    }

    // Requests access to address book data from the user
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {});

    // Build a predicate that searches for contacts that contain the phone number
    NSPredicate *predicate = [NSPredicate predicateWithBlock: ^(id record, NSDictionary *bindings) {
        ABMultiValueRef phoneNumbers = ABRecordCopyValue( (__bridge ABRecordRef)record, kABPersonPhoneProperty);
        BOOL result = NO;
        for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
            NSString *contactPhoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
            contactPhoneNumber = [[contactPhoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""];
            if ([contactPhoneNumber rangeOfString:phoneNumber].location != NSNotFound) {
                result = YES;
                break;
            }
        }
        CFRelease(phoneNumbers);
        return result;
    }];

    // Search the users contacts for contacts that contain the phone number
    NSArray *allPeople = (NSArray *)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
    NSArray *filteredContacts = [allPeople filteredArrayUsingPredicate:predicate];
    CFRelease(addressBook);

    return filteredContacts;
}