我目前正在处理 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/