ios - 快速获取用户的联系人电话号码

标签 ios swift swiftui swift5

我目前正在处理 SwiftUI 项目,并尝试获取用户联系人的电话号码。

我已成功收集联系人,并且可以打印他们的 givenName 以及 familyName,但我在尝试使用联系人 时遇到了问题电话号码

这是用于打印 givenName 的工作代码的核心:

store.enumerateContacts(with: request, usingBlock: {
    (contact, stopPointer) in print(contact.givenName)
})

使用https://stackoverflow.com/a/31615473/6642089作为一个工作示例,以下是我尝试打印联系人 phoneNumbers 的方法:

store.enumerateContacts(with: request, usingBlock: {
    (contact, stopPointer) in contact.
        for phone in contact.phoneNumbers {
            var label = phone.label
            if label != nil {
                label = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label!)
            }
            print("  ", label, phone.value.stringValue)
        }
    })

尝试迭代 contact.phoneNumbers 足以给我带来以下错误和很长的堆栈跟踪:

connection to service on pid 88497 named com.apple.contactsd: Exception caught during invocation of reply block to message 'encodedContactsAndCursorForFetchRequest:withReply:'.

Ignored Exception: A property was not requested when contact was fetched.

最佳答案

问题出在我的 CNContactFetchRequest 中。

最初,我只是询问联系人的名字。它看起来像:

let keys = [CNContactGivenNameKey]
let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])

答案是添加我需要在请求中使用的额外 key ,如下所示:

let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])

关于ios - 快速获取用户的联系人电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61681671/

相关文章:

ios - 如何通过多个 View 进行搜索?

ios ScrollView 的自动布局架构技巧

ios - 调用删除按钮Api后如何删除模型类中保存的数据?

xcode - 快速检测正确的文本字段以添加属性

swiftui-list - SwiftUI - 如何在编辑模式下避免列表中的行缩进,但不使用 onDelete? (附上代码/视频)

swiftui - 如何在 SwiftUI 中设置图像色调?

ios - 点击按钮时 functionCall 发生奇怪的崩溃

ios - 如何将插图添加到 UILabel (iOS Swift)?

ios - 使用正弦波(AVFoundation?)进行音频合成

ios - 在 iOS 14 上的 SwiftUI 中显示两次 View