ios - CNContactPickerViewController 仅检索选定的项目

标签 ios swift cncontact cncontactviewcontroller

委托(delegate)方法实现时:

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

用户可以从列表中选择联系人,然后会自动显示联系人详细信息。从联系人中选择指定字段后,CNContactPickerViewController 关闭。

问题是,如果有两个电话号码,并且用户专门选择了其中一个号码,则返回的 CNContactProperty 包括两个电话号码。

如何只提取用户点击的数字?

示例代码:

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
}

最佳答案

您的问题是您忽略了选定的属性。您正在直接访问联系人的所有电话号码。使用只有一个选定属性的 contactProperty 参数。

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
    }
}

如果您只想处理选定的电话号码,上面的代码很好。如果你想处理几种不同的属性类型,像下面这样的东西可能会更好:

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
    }
}

关于ios - CNContactPickerViewController 仅检索选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384843/

相关文章:

ios - Swift 2 - 更改标签颜色在​​模拟器中工作但不在 iPhone 上工作

swift - 将注释和图像添加到序列化的 VCF 联系人

ios - 通过 CNContact 从 iPhone 获取所有联系人列表时联系人图像未获取

ios - 如何 Hook subview 的 subview ?

ios - 合并将一个 Publisher 变成另一个 Publisher

swift - 初始 View Controller 应该调用 "deinit"吗?

IOS 在离开 Controller 时删除缓存 - kingfisher

swift - swift 中的 “This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread”

ios - 将 UIScrollView Delegate 和 UICollectionView Delegate 分配给同一个类

ios - 为什么 UINavigationBarAppearance 有一个 init(idiom :) initializer?