random random - 1 month ago 25
Swift Question

contactPickerDidCancel of CNContactPickerDelegate never called

When I select a contact using

CNContactPickerViewController
that does not have a number associated with it this delegate method is never called.

/*!
* @abstract Invoked when the picker is closed.
* @discussion The picker will be dismissed automatically after a contact or property is picked.
*/
optional public func contactPickerDidCancel(picker: CNContactPickerViewController)


If I select a contact that does have a number it is called. However from the method documentation it seems it should be called no matter what.

My issue is that I need to present a
UIAlertController
if the user selects a contact with no number. However I can only do this once the
CNContactPickerViewController
is dismissed.

I could get really hacky by using some logic in
viewDidAppear
but it seems there should be a cleaner way.

The only remaining delegate methods are:

/*!
* @abstract Singular delegate methods.
* @discussion These delegate methods will be invoked when the user selects a single contact or property.
*/
optional public func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact)
optional public func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty)

/*!
* @abstract Plural delegate methods.
* @discussion These delegate methods will be invoked when the user is done selecting multiple contacts or properties.
* Implementing one of these methods will configure the picker for multi-selection.
*/
optional public func contactPicker(picker: CNContactPickerViewController, didSelectContacts contacts: [CNContact])
optional public func contactPicker(picker: CNContactPickerViewController, didSelectContactProperties contactProperties: [CNContactProperty])


Which don't help in determining when the
CNContactPickerViewController
has actually left the screen.

(Xcode8 / swift2.3 / iOS10)

Answer

You can pop up an alert like this. You could also add a button to "try again" and relaunch the picker.

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        let name = CNContactFormatter.string(from: contact, style: .fullName)
        let phones = contact.phoneNumbers
        if phones.count == 0 {
            let alertController = UIAlertController(title: "Error", message: "\(name) has no phone numbers", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "Ok", style: .default) { (action) in })
            picker.dismiss(animated: false){
                self.present(alertController, animated: true) {}
            }
        }
        //Do stuff here
    }
Comments