Phone number format from country code on iOS

2019-04-15 19:27发布

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")
}

2条回答
劫难
2楼-- · 2019-04-15 19:56

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,

查看更多
干净又极端
3楼-- · 2019-04-15 20:05

I don't know whether this is a valid solution or not, you could try this

Say let your placeholder be 012345679 what I believe you could do is

  • Create a variable to store this placeholder
  • Parse this placeholder against the country that the user selects.
  • Set the parsed one as the placeholder in the textfield.
查看更多
登录 后发表回答