简体   繁体   中英

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.

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 .

Here is the core of working code used to print the 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 :

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:

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.

The problem was in my 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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