Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a CNContact phone number(s) as string in Swift?

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!

like image 221
Baylor Mitchell Avatar asked Mar 31 '16 20:03

Baylor Mitchell


1 Answers

I found the solution: (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String

like image 107
Baylor Mitchell Avatar answered Oct 05 '22 22:10

Baylor Mitchell