I am attempting to retrieve the names and phone number(s) of all contacts and put them into arrays with Swift in iOS. I have made it this far:
func findContacts() -> [CNContact] { marrContactsNumber.removeAllObjects() marrContactsName.removeAllObjects() let store = CNContactStore() let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey] let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch) var contacts = [CNContact]() do { try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in contacts.append(contact) self.marrContactsName.addObject(contact.givenName + " " + contact.familyName) self.marrContactsNumber.addObject(contact.phoneNumbers) print(contact.phoneNumbers) } catch let error as NSError { print(error.localizedDescription) } print(marrContactsName.count) print(marrContactsNumber.count) return contacts }
Once completed, marrContactsName
contains an array of all my contacts' names exactly as expected. i.e. "John Doe". However, marrContactsNumber
returns an array of values like
[<CNLabeledValue: 0x158a19950: identifier=F831DC7E-5896-420F-AE46-489F6C14DA6E, label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a19640: countryCode=us, digits=6751420000>>, <CNLabeledValue: 0x158a19a80: identifier=ECD66568-C6DD-441D-9448-BDEDDE9A68E1, label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a199b0: countryCode=us, digits=5342766455>>]
I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value. Thanks!
I found the solution: (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With