联系人有多个邮件时的 CNContactPickerViewController

CNContactPickerViewController when contact has multiple mails

我正在使用 CNContactPickerViewController 让用户 select his/her 联系人之一的电子邮件

let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
contactPicker.predicateForSelectionOfContact = NSPredicate(format: "emailAddresses.@count > 0")
contactPicker.displayedPropertyKeys = [CNContactNicknameKey, CNContactEmailAddressesKey]

当联系人只有一封邮件时,一切顺利

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

    if let _mail = contact.emailAddresses.first?.value as String? {
        self.personWasSelected(with: _mail)
    }
}

但有时其中一位联系人有不止一封邮件,我怎样才能让用户 select 处理其中一封?

好的,通过试错找到了解决方案...

我同时实施了:

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
    if let _mail = contactProperty.value as? String {
        self.personWasSelected(with: _mail)
    }
}

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

    if let _mail = contact.emailAddresses.first?.value as String? {
        self.personWasSelected(with: _mail)
    }
}

但应该只实现了第一个

要让用户选择要发送给 select 的电子邮件地址,请设置

picker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
picker.predicateForSelectionOfContact = NSPredicate(format: "emailAddresses.@count == 1")

这种方式,适用于只有一封电子邮件的用户

contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)

接到电话,但对于拥有多个电子邮件的用户,会显示联系方式并将 selected 电子邮件传递给

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

注意 CNContactProperty 也有 .contact 属性。