Search code examples
iosswift3libphonenumber

Phone number format from country code on iOS


I need to display phone number format as placeholder in UITextField. How can I do that?

For country selection I'm using below mentioned library and it provides me country flag and country code against user selected country.

https://github.com/NikKovIos/NKVPhonePicker

After selecting a country I need to display phone number format for that selected country and on submission of that phone number I have to validate the phone number.

I also find that third party (PhoneNumberKit) which is inspired by google's libphonenumber but it is for validating, it do not provide expected phone number format against country code. Below is the link.

https://github.com/marmelroy/PhoneNumberKit

Update 1: Tried this and getting Generic parser error

let phoneNumberKit = PhoneNumberKit()

do {
    let phoneNumber = try phoneNumberKit.parse("+921230123456")
}
catch {
    print("Generic parser error")
}

Update 2: Updated code, still getting exception

let phoneNumberKit = PhoneNumberKit()

do {
    let phoneNumber = try phoneNumberKit.parse("1230123456", withRegion: "FR", ignoreType: false)
    let formatedNumber = phoneNumberKit.format(phoneNumber, toType: .international)
    print(formatedNumber)
}
catch {
    print("Generic parser error")
}

Solution

  • For those who wanna do the same thing, I used two different 3rd parties to achieve the functionality.

    1. NKVPhoneNumber
    2. SHSPhoneComponent

    NKVPhoneNumber is used to select country code, i've modified it a bit a introduced phone_format in the Meta Data. Once selected a country from the list it return a Country object which includes Code, Extension, Flag and format_placeholder

    SHSPhoneComponent then use that format_placeholder for validation of the format.

    import SHSPhoneComponent
    import NKVPhonePicker
    
    @IBOutlet weak var phoneTF: SHSPhoneTextField!
    @IBOutlet weak var phoneFlag: NKVPhonePickerTextField!
    @IBOutlet weak var lblCountryCode: UILabel!
    
    //MARK: - NKV callback delegates
    
    func countriesViewController(_ sender: CountriesViewController, didSelectCountry country: Country) {
        //
    
        phoneTF.formatter.setDefaultOutputPattern(country.formatPattern)
        phoneTF.text = ""
        phoneTF.placeholder = country.formatPatternPlaceHolder
        countryCode = "+\(country.phoneExtension)"
    
        lblCountryCode.text = countryCode
    }
    

    Note: I've converted NVKPhoneNumber to Swift 4.0,