ios - 如何使用 CNContactPickerViewController 获取地址和联系人?

标签 ios swift contacts-framework

我正在尝试使用更现代的 CNContactPickerViewController 来选择联系人。如果联系人有多个地址,我希望用户只能选择其中一个地址。如果专门选择了一个地址,我还想获得 CNContact 对象。

我可以使用已弃用的 ABPeoplePickerNavigationControllerDelegate 来执行此操作,其中此委托(delegate)函数可用:

func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier)

但是,当使用 CNContactPickerViewController 时,只有这个相关的委托(delegate)函数可用:

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

请注意,没有返回 CNContact 对象。我在 contactProperty 中获取了 CNPostalAddress,但我没有收到所属联系人的记录。

这是我在 ABPeoplePickerNavigationController 中使用的代码:

    let peoplePicker = ABPeoplePickerNavigationController()

    peoplePicker.peoplePickerDelegate = self

    peoplePicker.displayedProperties = [NSNumber(value: kABPersonAddressProperty as Int32), NSNumber(value: kABPersonBirthdayProperty as Int32)]

    peoplePicker.predicateForSelectionOfPerson = NSPredicate(format: "postalAddresses.@count <= 1")

    peoplePicker.modalPresentationStyle = UIModalPresentationStyle.currentContext

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

...这是 CNContactPickerViewController 的代码:

    let contactPicker = CNContactPickerViewController()

    contactPicker.delegate = self

    contactPicker.displayedPropertyKeys = [CNContactPostalAddressesKey, CNContactBirthdayKey]

    contactPicker.predicateForSelectionOfContact = NSPredicate(format: "postalAddresses.@count <= 1")

    contactPicker.modalPresentationStyle = UIModalPresentationStyle.currentContext

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

所以,对我来说,新的 Contacts Framework 中似乎不再提供相同的功能,但我正在检查这里是否遗漏了什么。

最佳答案

Note that there is no CNContact object returned. I get the CNPostalAddress in the contactProperty, but I don't receive the record of the owning contact.

CNContact 对象可以从 CNContactPropertycontact 属性中获取,所以……

However, when using CNContactPickerViewController, only this relevant delegate function is available:

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

…实现这个委托(delegate)方法可以让你做你想做的事。但是您要确保您没有实现其他委托(delegate)方法,例如:

func contactPicker(CNContactPickerViewController, didSelect: CNContact)

这将在选择联系人(而不是其属性)时关闭选择器。

关于ios - 如何使用 CNContactPickerViewController 获取地址和联系人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39628346/

相关文章:

ios - 函数返回一个返回函数的函数

ios - 从联系人发送短信失败

ios - 我应该在我的代码中更改什么以访问所有联系人,而不仅仅是 1 个与 swift 的联系人?

ios - Monotouch 中是否有 NSString 的 "stringByReplacingCharactersInRange"方法?

iphone - 用动画替换 window.rootViewController 部分有效

ios - 应用程序终止时获取用户的位置

ios - 检索到的数据没有附加到我的数组 swift4

ios8 - iOS 8.0 和 9.0 中的地址簿和联系人框架

IOS9 联系人框架无法更新链接的联系人

ios - 链接器命令失败,退出代码为 1(使用 -v 查看调用)Apple Mach 链接器错误