Localized phone number formatting

2019-01-18 04:38发布

I've looked into NSFormatter, NSNumberFormatter, and the other formatting classes, but can't find a build into solution. I need to format phone numbers depending on the country code.

For instance, for US, I get a string such as +16313938888 which I need to format to look like +1(631)393-8888. The problem is I need to do this for all formats. Netherlands, I receive a string +31641234567 which will be +31(6)41 23 45 67 (something like that).

Hardcoding for 200+ countries is too tedious and I really don't know all the format rules. Is there something in the docs I'm overlooking or does anyone know of an open source class that manages this?

5条回答
趁早两清
2楼-- · 2019-01-18 04:56

You can try this:

    let phoneNumber : CNPhoneNumber
    let digits = phoneNumber.performSelector("digits").takeRetainedValue() as! String

It gives you directly the string, without formatting, with the phone number. However if the number is saved with international prefix, you will have it also in the resulted string.

查看更多
狗以群分
3楼-- · 2019-01-18 05:00

Unfortunately iOS does not have any public APIs for this. You can try to integrate libphonenumber that is a complete implementation for parsing and formatting international phone numbers. It has a C++ version so theoretically you can cross-link with it.

查看更多
Lonely孤独者°
4楼-- · 2019-01-18 05:10

You definitely don't want to hard-code all of the various country formats. There are typically 3-5 formats per country. Instead, use a format database (such as a plist) and write code to format the number based on the given country code.

A good international format property list 'UIPhoneFormats.plist' can be found here: https://code.google.com/p/iphone-patch/source/browse/trunk/bgfix/UIKit.framework/PhoneFormats/UIPhoneFormats.plist?r=7

In that list, '$' allows any character, '#' must be a number, and the '(space) ', '(', ')' and '-' are inserted between numbers. Non-numeric characters typed by the user hint to the desired format.

I've shared my phone number formatter class, inspired by Ahmed Abdelkader's work, at https://github.com/lathamglobal/iOS-Phone-Number-Formatter . It is a very small, single-class international phone number formatter that uses the plist just mentioned.

查看更多
小情绪 Triste *
5楼-- · 2019-01-18 05:14

Try this Google solution - https://github.com/me2day/libPhoneNumber-iOS They have ports for C++, Java, Objective-C and others.

查看更多
虎瘦雄心在
6楼-- · 2019-01-18 05:16

See https://github.com/rmaddy/RMPhoneFormat for an iOS specific solution.

查看更多
登录 后发表回答