How can I pick a contact phone number in iOS?

4.5k Views Asked by At

I know how to pick a contact in iOS (using the CNContactPickerViewController), but how can I pick a specific phone number for a contact, instead of the contact itself, as a whole? That should be possible, according to the docs, but I didn't find out how.

EDIT: here's my code

CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];

contactPicker.delegate = self;
contactPicker.displayedPropertyKeys = @[CNContactGivenNameKey, CNContactImageDataAvailableKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactThumbnailImageDataKey, CNContactIdentifierKey];

[self presentViewController:contactPicker animated:YES completion:nil];

So, I do set the displayedProperties, but the result is the same, even if I choose only CNContactPhoneNumbersKey, I'm not presented with all contact's numbers so that I can choose a speicific number.

What am I missing?

EDIT 2: the callback methods, as requested. I don't know of what significance they are, but nevertheless.

-(void) contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
  //NSLog(@"Contact : %@",contact);
  NSString* contactName = [NSString stringWithFormat:@"%@%@%@", contact.givenName, @" ", contact.familyName];
  [currentButton setTitle:contactName forState:UIControlStateNormal];
  [currentName setText:contactName];
...
}

-(void) contactPickerDidCancel:(CNContactPickerViewController *)picker {
  //NSLog(@"Cancelled");
}
2

There are 2 best solutions below

6
On BEST ANSWER

OK, here's the answer:

First of all, use only the property that you want to select in the displayedPropertyKeys (in this case that is CNContactPhoneNumbersKey), and make sure to implement ALL delegate methods (i.e. both didSelectContact - when the contact has only one phone number, and didSelectContactProperty - when the contact has more than one phone number).

Furhtermore, restrict the contact selection by setting:

contactPicker.predicateForEnablingContact = [NSPredicate predicateWithFormat:@"phoneNumbers.@count > 0"];
contactPicker.predicateForSelectionOfContact = [NSPredicate predicateWithFormat:@"phoneNumbers.@count == 1"];
contactPicker.predicateForSelectionOfProperty = [NSPredicate predicateWithFormat:@"key == 'phoneNumbers'"];
6
On

You need to set the displayedKeys property of the CNContactPicker. If you don't set any keys, you can only select a contact. If you set the keys, then you choose a contact then you select a desired contact property.

Implement the appropriate delegate methods to complete the process.