iosswiftphone-numberphonenumberkit

How to determine region from the phone number string?


I tried using PhoneNumberKit and couldn't find any proper api which would give me the region name. I need the region from the phone number so that I can display the appropriate flag. For example using this:

  let phoneNumber = try phoneNumberKit.parse("+12563335956")
  let regionCode = phoneNumberKit.countries(withCode: phoneNumber.countryCode)?.first
  print("region code is: " , regionCode) 

// US phone number with +1 prefix, but it prints "AG" which is wrong.


Solution

  • As you said, the country code can tell you which flag to use.

    let phoneNumber = try phoneNumberKit.parse("+1 970162651778")
    let regionCode = phoneNumberKit.getRegionCode(of: phoneNumber)
    
    print(regionCode) // Optional("US")
    

    You can get the country region code using the country code of the phone number.