iosswiftcncontactcncontactviewcontroller

CNContactPickerViewController Retrieve ONLY Selected Item


When the delegate method is implemented:

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

The user is able to select a contact from the list, then the contact details automatically appear. Upon selecting the specified field from the contact, the CNContactPickerViewController dismisses.

The issue is that if there are two phone numbers, and the user specifically selects one of the numbers, the CNContactProperty returned includes both phone numbers.

How do I extract only the number the user tapped on?

Example code:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
    contactProperty.contact.phoneNumbers //the numbers are an array so I am not able to see which one the user selected
}

Solution

  • Your issue is that you are ignoring the selected property. You are directly accessing all of the phone numbers on the contact. Make use of the contactProperty parameter which has just the one selected property.

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
        // See if the user selected a phone number
        if let phone = contactProperty.value as? CNPhoneNumber {
            let number = phone.stringValue
        }
    }
    

    The above is fine if you only want to deal with chosen phone numbers. If you want to handle several different property types, something like the following is probably better:

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
        switch contactProperty.key {
        case CNContactPhoneNumbersKey:
            if let phone = contactProperty.value as? CNPhoneNumber {
                let number = phone.stringValue
                // do something
            }
        // case ...: // some other type
        default:
            break
        }
    }