我使用以下代码已有几年了,并且一直可以正常工作,但是在iOS 6中似乎不再可用了。如何获取iOS 6设备上所有联系人的列表?

ABAddressBookRef myAddressBook = ABAddressBookCreate();
        NSMutableArray *people = (__bridge_transfer NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
        CFRelease(myAddressBook);

        // repeat through all contacts in the inital array we loaded
        for(int i=0; i<[people count]; i++)
        {
            NSString *aName;
            NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonFirstNameProperty);
            NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonLastNameProperty);

            if (([firstName isEqualToString:@""] || [firstName isEqualToString:@"(null)"] || firstName == nil) &&
                ([lastName isEqualToString:@""] || [lastName isEqualToString:@"(null)"] || lastName == nil))
            {
                // do nothing
            }
            else
            {
                aName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

                if ([firstName isEqualToString:@""] || [firstName isEqualToString:@"(null)"] || firstName == nil)
                {
                    aName = [NSString stringWithFormat:@"%@", lastName];
                }

                if ([lastName isEqualToString:@""] || [lastName isEqualToString:@"(null)"] || lastName == nil)
                {
                    aName = [NSString stringWithFormat:@"%@", firstName];
                }

                [self.tableItems addObject:aName];
            }

        }

        [self.tableItems sortUsingSelector:@selector(compare:)];

最佳答案

在ios6中,您需要请求读取通讯簿的权限,否则将得到nil。使用这样的东西:

- (BOOL)askContactsPermission {
    __block BOOL ret = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS6

        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRef addressBook = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            ret = granted;
            dispatch_semaphore_signal(sema);
        });
        if (addressBook) {
            CFRelease(addressBook);
        }

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else { // we're on iOS5 or older
        ret = YES;
    }

    return ret;
}

如果此方法返回否,那么运气不好,您将无法访问AB。我在这里用信号灯锁定,因为如果用户不允许使用AB,我不想继续使用我的应用程序。还有其他方法,只需检查API。

09-07 12:05