Localized phone number formatting

前端 未结 5 2046
时光说笑
时光说笑 2020-12-09 18:36

I\'ve looked into NSFormatter, NSNumberFormatter, and the other formatting classes, but can\'t find a build into solution. I need to format phone n

相关标签:
5条回答
  • 2020-12-09 19:01

    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.

    0 讨论(0)
  • 2020-12-09 19:02

    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.

    0 讨论(0)
  • 2020-12-09 19:18

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

    0 讨论(0)
  • 2020-12-09 19:21

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

    0 讨论(0)
  • 2020-12-09 19:21

    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.

    0 讨论(0)
提交回复
热议问题