Formatting Phone Numbers on an iPhone

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

The following is a guest post by Dulio Denis and originally appeared on his blog. Dulio is currently in the iOS-000 class at The Flatiron School. You can follow him on Twitter here.

With my Corporate Directory CapStone project I found myself needing to format a phone number in phone fields like cell phone, home phone, office phone, etc.  I was surprised to find this is not as easy on an iPhone as you may think.  Even though clearly Apple has this functionality in Contacts they have no Public API for phone formatting.  You may think what’s the big deal anyhow. Well, in the US you could have a leading 1 or not and you want to be consistent with area code segmentation and then there are international numbers.  I started looking on stackoverflow but thought there ought to be a better way than implementing my own NSFormatter.After looking around I found a good GitHub project by Willy Shark, A.K.A. Serheo Shatunov, called ( “SHSPhoneComponent”).  The good news is it also has a ( “SHSPhoneComponent CocoaPod”).

In this post I’ll outline how to integrate this CocoaPod into your project.

  1. First, update your Podfile with the below and do a pod update:

Blog post image: tumblr_inline_mwkm7dLOlx1rtan47.png
  1. Then in your Storyboard or Nib file create a UITextFiled for the phone number to be formatted.  I was using UILabels which do not work as these are UITextField and NSFormatter subclasses for formatting phone numbers. Connect your UITextField(s) to the proper View’s Outlet(s). Since we are using a custom class we need to make the @property of the phone labels look something like:

Blog post image: tumblr_inline_mwkm6vz06l1rtan47.png

Then using the Identity Inspector set the custom class of the UITextField to this SHSPhoneTextField.

  1. In your View’s include the following libraries:

Blog post image: tumblr_inline_mwkm6bNPEL1rtan47.png
  1. In your View’s ViewDidLoad method

Blog post image: tumblr_inline_mwkm5q7AKq1rtan47.png

One thing to note is that in line 2 above the addOutputPattern: requires a regular expression in order to have a pattern to match. One site I found which helped me test my regex with my data was a regular expression calculator at ( “Rubular”).

Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Flatiron School Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat