CNContactPickerViewController when contact has multiple mails

1.7k views Asked by At

I'm using a CNContactPickerViewController to let the user select the email of one of his/her contacts

let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
contactPicker.predicateForSelectionOfContact = NSPredicate(format: "emailAddresses.@count > 0")
contactPicker.displayedPropertyKeys = [CNContactNicknameKey, CNContactEmailAddressesKey]

When the contact has only one mail, everything goes well

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

    if let _mail = contact.emailAddresses.first?.value as String? {
        self.personWasSelected(with: _mail)
    }
}

But sometimes one of the contacts has more than one mail, how can I let the user select on one of those?

2

There are 2 answers

0
mtet88 On BEST ANSWER

Ok, found the solution by trial-error...

I was implementing both:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
    if let _mail = contactProperty.value as? String {
        self.personWasSelected(with: _mail)
    }
}

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

    if let _mail = contact.emailAddresses.first?.value as String? {
        self.personWasSelected(with: _mail)
    }
}

But only the first one should have been implemented

0
bbjay On

To let a user choose which email address to select, set

picker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
picker.predicateForSelectionOfContact = NSPredicate(format: "emailAddresses.@count == 1")

This way, for users with only one email

contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)

gets called, but for users with more than one email, the contact detail is presented and the selected email is passed to

contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty)

Note that CNContactProperty also has the .contact attribute.