How to show multiple phone numbers if exists in CNContactPickerViewController

684 Views Asked by At

in my app I am using CNContactPickerViewController for getting contacts. User can select multiple contacts so I implemented following delegate methods.

 func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        var tempContacts = [Contact]()
        contacts.forEach { (contact) in
            if let phoneNumber = contact.phoneNumbers.first {
                let contact = Contact(name: "\(contact.givenName) \(contact.familyName)" , phoneNumber: "\(phoneNumber.value.stringValue)")
                tempContacts.append(contact)
            }
        }
        selectedContacts = tempContacts
        _ = Contact.save(contacts: selectedContacts)
    }
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("Cancel contact picker")
    }

However, some users are complaining about not able to see and select if contact has more than one phone number. Is it possible to show contacts that have multiple numbers?

1

There are 1 best solutions below

1
Claudio On

You're only using the first phone number of a contact:

if let phoneNumber = contact.phoneNumbers.first {
    let contact = Contact(name: "\(contact.givenName) \(contact.familyName)" , phoneNumber: "\(phoneNumber.value.stringValue)")
    tempContacts.append(contact)
}

What if you map all the phone numbers to an array of contacts using the map method:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    var tempContacts = [Contact]()
    contacts.forEach { (contact) in
        let contactPhoneNumbers = contact.phoneNumbers.map { Contact(name: "\($0.givenName) \($0.familyName)" , phoneNumber: "\($0.value.stringValue)") }
        tempContacts.append(contentsOf: contactPhoneNumbers)
    }
    selectedContacts = tempContacts
    _ = Contact.save(contacts: selectedContacts)
}