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

35,404

Solution 1

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

Solution 2

you can get contact.phoneNumbers from CNLabeledValue:

for phoneNumber in contact.phoneNumbers {
  if let number = phoneNumber.value as? CNPhoneNumber,
      let label = phoneNumber.label {
      let localizedLabel = CNLabeledValue.localizedStringForLabel(label)
      print("\(localizedLabel)  \(number.stringValue)")
  }
}

Solution 3

/* Get only first mobile number */

    let MobNumVar = (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String
    print(MobNumVar)

/* Get all mobile number */

    for ContctNumVar: CNLabeledValue in contact.phoneNumbers
    {
        let MobNumVar  = (ContctNumVar.value as! CNPhoneNumber).valueForKey("digits") as? String
        print(MobNumVar!)
    }

 /* Get mobile number with mobile country code */

    for ContctNumVar: CNLabeledValue in contact.phoneNumbers
    {
        let FulMobNumVar  = ContctNumVar.value as! CNPhoneNumber
        let MccNamVar = FulMobNumVar.valueForKey("countryCode") as? String
        let MobNumVar = FulMobNumVar.valueForKey("digits") as? String

        print(MccNamVar!)
        print(MobNumVar!)
    }

Solution 4

Here is how you do it in swift 4

func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {

    if let phoneNo = contactProperty.value as? CNPhoneNumber{
        txtPhone.text = phoneNo.stringValue
    }else{
        txtPhone.text=""
    }
}

Solution 5

Here's a Swift 5 solution.

import Contacts

func sendMessageTo(_ contact: CNContact) {

    let validTypes = [
        CNLabelPhoneNumberiPhone,
        CNLabelPhoneNumberMobile,
        CNLabelPhoneNumberMain
    ]

    let numbers = contact.phoneNumbers.compactMap { phoneNumber -> String? in
        guard let label = phoneNumber.label, validTypes.contains(label) else { return nil }
        return phoneNumber.value.stringValue
    }

    guard !numbers.isEmpty else { return }

    // process/use your numbers for this contact here
    DispatchQueue.main.async {
        self.sendSMSText(numbers)
    }
}

You can find available values for the validTypes array in the CNPhoneNumber header file.

They are:

CNLabelPhoneNumberiPhone
CNLabelPhoneNumberMobile
CNLabelPhoneNumberMain
CNLabelPhoneNumberHomeFax
CNLabelPhoneNumberWorkFax
CNLabelPhoneNumberOtherFax
CNLabelPhoneNumberPager
Share:
35,404
Baylor Mitchell
Author by

Baylor Mitchell

Updated on April 09, 2021

Comments

  • Baylor Mitchell
    Baylor Mitchell about 3 years

    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!