4

I would like to be able to store a phone number in a standard way, e.g. just the digits (potentially with the '+' for the country code), something like these examples...

"17185555555"
"+17185555555"
"+447788888888"

... but I'd like to be able to DISPLAY it to a user in a properly formatted way, e.g.

"1 (718) 555-5555"
"+1 (718) 555-5555"
"+44 (7788) 888888"

...WITHOUT having to rely on a CNContactViewController to format it.

Obviously doing this just for US/Canada numbers would be easy - it's just one standard format - but I'd like it to be generic so it can work for numbers from any country. I know this question gives an answer for US/Can numbers only.

I know that I could use a CNContactViewController to display the number in the correct format, e.g.

let newContact = CNMutableContact()
newContact.givenName = "John"
newContact.familyName = "Smith"
newContact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue:"17185555555"))]
let contactView = CNContactViewController(forContact: newContact)
self.presentViewController(contactView, animated: true, completion: nil)

This will show the number on screen properly formatted, i.e.

1 (718) 555-5555

... so I know that something in the framework can do it. (This approach works for other country phone number formats, as long as you prefix the number with the right country code - e.g. "+44...")

From various other questions I know that I can get the raw digits and country code out of a CNContact, e.g. (following above example)

for pNumber: CNLabeledValue in newContact.phoneNumbers {
    let value  = pNumber.value as! CNPhoneNumber
    let cc = value.valueForKey("countryCode") as? String
    let digits = value.valueForKey("digits") as? String
    print("cc:" + cc + ", " + digits)
}

... but this will just show the unformatted string again - not what I am looking for in this case.

Any help or other recommended approaches really appreciated!

Community
  • 1
  • 1
nickpharris
  • 385
  • 5
  • 17
  • Seems to be a duplicate of http://stackoverflow.com/questions/6052966/phone-number-formatting – matt Sep 02 '16 at 21:00
  • I saw that question (and will link to it now), but I believe I am right in saying that works for US/Can format numbers only, which is not what I am looking for. – nickpharris Sep 02 '16 at 21:01
  • I don't know what you mean by "that". There are answers there that show just what it would take to provide a locale-aware phone number formatter. – matt Sep 02 '16 at 22:46

1 Answers1

2

My answer proposes another lib

You can format your numbers with this lib.

And you can use like this:

let phoneNumber: NBPhoneNumber = try phoneUtil.parse("17185555555", defaultRegion: yourRegion)
let formattedString: String = try phoneUtil.format(phoneNumber, numberFormat: .E164)
Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49