0

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?

atalayasa
  • 3,310
  • 25
  • 42

1 Answers1

0

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)
}
Claudio
  • 5,078
  • 1
  • 22
  • 33
  • I already thought to add multiple phone numbers if it's exist but I would like to show the user while selecting on the list. – atalayasa Nov 03 '20 at 11:38