Skip to content

Localized phone number formatting from string or number.

Apple didn’t give us much help when it comes to formatting phone numbers however they do have their own API to do this. We cannot use their private API’s so we must duplicate the work. Here is a small example of how you can subclass NSFormatter and format a phone number from an NSString or NSNumber object.


- (NSString *)formattedPhoneNumberFromString:(NSString *)aNumber
{
if (!aNumber || !aNumber.length)
{
return aNumber;
}

NSString * ret = nil;

BOOL enUS = [[self.locale localeIdentifier] compare:@"en_US"] == NSOrderedSame;

if (enUS)
{
NSRange range = NSMakeRange(3, 3);

NSString * part1 = [aNumber substringToIndex:3];
NSString * part2 = [aNumber substringWithRange:range];
NSString * part3 = [aNumber substringFromIndex:6];

ret = [NSString stringWithFormat:@"(%@) %@-%@", part1, part2, part3];
}
else
{
ret = aNumber;
}

return ret;
}

and

- (NSString *)formattedPhoneNumberFromNumber:(NSNumber *)aNumber
{
if (!aNumber)
{
return @"";
}

return [self formattedPhoneNumberFromString:[aNumber stringValue]];
}

As you may notice you can utilize device locale specifics to add international support.

Categories: cocoa, iphone.

Comment Feed

3 Responses

  1. Hello from Russia!
    Can I quote a post in your blog with the link to you?

  2. Sure, enjoy!

  3. One again, your articles is very good.thank you!very much.



Some HTML is OK

or, reply to this post via trackback.