简体   繁体   English

Swift 获取用户的联系人电话号码

[英]Swift Fetching User's Contacts Phone Numbers

I'm currently working with a SwiftUI project and am attempting to get the phone numbers of the User's contacts.我目前正在使用 SwiftUI 项目,并试图获取用户联系人的电话号码。

I've successfully gathered the contacts and can print their givenName as well as their familyName , but I have been experiencing issues trying to work with the contacts phoneNumbers .我已经成功地收集了联系人并且可以打印他们的givenName以及他们的familyName ,但是我在尝试使用联系人phoneNumbers时遇到了问题。

Here is the core of working code used to print the givenName :这是用于打印givenName的工作代码的核心:

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

Using https://stackoverflow.com/a/31615473/6642089 as an example to work off of, here is how I'm attempting to print out the contacts phoneNumbers :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)
        }
    })

Attempting to iterate over the contact.phoneNumbers is enough to give me the following error with a very long stacktrace:尝试遍历 contact.phoneNumbers 足以给我一个非常长的堆栈跟踪的以下错误:

connection to service on pid 88497 named com.apple.contactsd: Exception caught during invocation of reply block to message 'encodedContactsAndCursorForFetchRequest:withReply:'.连接到名为 com.apple.contactsd 的 pid 88497 上的服务:在调用消息“encodedContactsAndCursorForFetchRequest:withReply:”的回复块期间捕获异常。

Ignored Exception: A property was not requested when contact was fetched.忽略的异常:获取联系人时未请求属性。

The problem was in my CNContactFetchRequest .问题出在我的CNContactFetchRequest中。

Originally, I was only asking for the contacts given name.最初,我只是询问联系人的名字。 It looked like:它看起来像:

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

The answer was this add additional keys that I needed to utse within my request like so:答案是这添加了我需要在我的请求中使用的额外密钥,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM