iOS获取用户联系人不包括商家

时间:2014-08-20 03:07:54

标签: ios abrecord

我有一个正在加载所有用户联系人的应用。我想排除任何业务,但我似乎找不到确定联系人是否是公司的方法。

我最初考虑检查“公司”字段是否包含第一个和最后一个名称时的值,但我无法从ABRecord中找到此属性。

以下是我如何抓住名字和姓氏:

NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取公司名称:

NSString *company = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonOrganizationProperty);

您可以根据是否有组织名称来过滤您的数组,但不能使用名字或姓氏。


但是,如果你想排除企业,你并不真正关心公司名称(因为人们可能有公司名称,但企业通常没有姓/名)。只需过滤您的记录,只包括具有名字和/或姓氏的记录:

CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

if (error) {
    NSLog(@"Address book creation failure: %@", CFBridgingRelease(error));
    return;
}

ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();

if (status == kABAuthorizationStatusDenied) {
    // authorization previously denied ... tell user to go to settings and authorize access
    NSLog(@"kABAuthorizationStatusDenied");
    return;
}

ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
    if (granted) {
        NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, NULL, kABPersonSortByLastName));

        // if you didn't want to sort, just use
        //
        // NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));

        NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id person, NSDictionary *bindings) {
            NSString *firstName = CFBridgingRelease(ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonFirstNameProperty));
            NSString *lastName  = CFBridgingRelease(ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonLastNameProperty));

            return (firstName || lastName);
        }];

        NSArray *peopleNotCompanies = [allPeople filteredArrayUsingPredicate:predicate];

        // You now have an array of `ABRecordRef` associated with
        // those contacts with first or last name
    } else {
        // authorization only just now denied ... tell user to go to settings and authorize access
        NSLog(@"Access not granted: %@", CFBridgingRelease(error));
    }
});

或者,您可以查看kABPersonKindProperty

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id person, NSDictionary *bindings) {
    CFNumberRef recordType = ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonKindProperty);
    BOOL isCompany = (recordType == kABPersonKindOrganization);
    CFRelease(recordType);

    return !isCompany;
}];

您是否愿意依赖此kABPersonKindProperty取决于您。我不确定它是否适当填充了Microsft Exchange这样的来源,更不用说所有最终用户是否总是点击相应的复选框。