iosios8ios8.1addressbookui

How can I get the contact ID


I have a problem with getting the contact ID from the address book.

My .m file:

-(IBAction)test:(id)sender
{
    ABPeoplePickerNavigationController* picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    ABRecordID recordID = ABRecordGetRecordID(person);
    label.text = [NSString stringWithFormat:@"%d", recordID];

}

-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

I imported the AddressBook and the AddressBookUI into the .h file. It works all but I get the wrong ID. Everytime I only get the ID -1 and that stands for error.

Hope you can help me.

Thanks a lot, Christian


Solution

  • In iOS 8, it no longer automatically requests permission for the address book when just showing the people picker. (The idea is that is that the picker, alone, is not really giving the app access to your contacts, so no permission should be required. It offers low-friction UI when app isn't really getting the contact details.)

    But, in your case, you really are trying to programmatically retrieve information about the contact. For that, you do need permission. So, prior to presenting the picker, you might want to ask permission to the address book:

    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    if ((status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted)) {
        NSLog(@"User previously denied permission; show error message that they must go to settings and give this app permission");
        return;
    } else if (status == kABAuthorizationStatusNotDetermined) {
        CFErrorRef error;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
        if (!addressBook) {
            NSLog(@"unable to open address book: %@", CFBridgingRelease(error));
            return;
        }
    
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            if (granted) {
                NSLog(@"OK");
            } else {
                NSLog(@"Not ok");
            }
    
            CFRelease(addressBook);
        });
    }