Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pick a contact phone number in iOS?

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");
}
like image 205
Eir Avatar asked Jan 12 '17 21:01

Eir


1 Answers

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'"];
like image 120
Eir Avatar answered Nov 05 '22 00:11

Eir