Search code examples
swift3contactsios10.3

Multiple Selections from ContactUI in Swift 3


I'm very new to coding in Swift and trying to teach myself. I am having trouble figuring out how to enable multiple selections from the ContactPicker View UI in Swift 3.

From reading the documentation, it seems that to enable multiple selection I should use [CNContactProperty], but this is ambiguous. When I do this I am unable to call the property to print the givenName and the value because these are not members of the array. Also when I use the syntax of [CNContactProperty] my picker view is not showing a "Done" button to end selections. Cancel is my only option to get out of the picker view.

I have found many answers for previous versions of Swift but am interested in how to employ this functionality in Swift 3. Ultimately I am trying to pre-populate the contacts field in a UIMessageComposer to send a message to multiple contacts from an array with one push of the send button.

// this is the code that works for a single selection
import UIKit
import ContactsUI
import Contacts

class MainViewController: UIViewController, CNContactPickerDelegate {

// select Contacts to message from "Set Up" Page
@IBAction func pickContacts(_ sender: Any) {

    let contactPicker = CNContactPickerViewController()

    contactPicker.delegate = self
    contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey]

    self.present(contactPicker, animated: true, completion: nil)

}

//allow contact selection and dismiss pickerView
func contactPicker(_ picker: CNContactPickerViewController, didSelect contactsProperty: CNContactProperty) {
    let contact = contactsProperty.contact
    let phoneNumber = contactsProperty.value as! CNPhoneNumber

    print(contact.givenName)
    print(phoneNumber.stringValue)

}

Solution

  • In your CNContactPickerDelegate implementation, you have implemented:

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

    Which is called when a specific property is selected. But if you want to select multiple contacts, you need to implement:

    contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact])
    

    That returns an array of selected contacts. So your delegate implementation method might look something like this:

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        for contact in contacts {
            let phoneNumber = contact.value(forKey:CNContactPhoneNumbersKey)
            print(contact.givenName)
            print(phoneNumber)
        }
    }
    

    Of course, the phoneNumber variable will include an array of phone numbers and you'd need to loop through the array to get a specific number.