Always get ISO 639-2 (three-digit) language code on iOS?

I am working on a project that requires a three letter language code (ISO 639-2) to access the REST service. I was hoping to use the current language setting using [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] . Unfortunately, this method prefers to return two letter codes (ISO 639-1). Is there a way to force NSLocale to return updated codes, or is there another way I can use to convert two-letter code to three-letter code?

+4
ios localization
source share
4 answers

No, you cannot do this. You must convert them manually, and it is not very simple.

+5
source share

Check the Github code for the category in NSLocale to get the ISO 639.2 language code. It is as simple as:

 [[NSLocale currentLocale] ISO639_2LanguageIdentifier]; 
+8
source share

I needed a similar conversion for ISO 3166-1 country codes. iOS gave me a 2 letter code, but I needed a 3 letter code. Here is my solution:

Sample example code (if you have an iso-countries.json file in the lukes GIT project format)

 import UIKit import CoreTelephony class CountryCode { internal var _countries: [String: [AnyHashable: Any]]? internal var countries: [String: [AnyHashable: Any]]? { get { if _countries == nil { _countries = countriesDictionary() } return _countries } } func convertToThreeCharacterCountryCode(twoCharacterCountryCode: String) -> String? { let country = countries?[twoCharacterCountryCode.uppercased()] return country?["alpha-3"] as? String } fileprivate func countriesDictionary() -> [String: [AnyHashable: Any]] { var countries = [String: [AnyHashable: Any]]() guard let url = Bundle.main.url(forResource: "iso-countries", withExtension: "json") else { return countries } do { let data = try Data(contentsOf: url) if let dictionaries = try JSONSerialization.jsonObject(with: data, options: []) as? [[AnyHashable: Any]] { for countryDictionary in dictionaries { if let key = countryDictionary["alpha-2"] as? String { countries[key] = countryDictionary } } return countries } return countries } catch { return countries } } } 

You might consider making this a Singleton class, so countries only need to load once. I didn’t do it the way I didn’t want to keep the countries in my memory (in my application this was necessary only once at startup).

0
source share

In Swift, it's simple:

 let currentLocale = NSLocale.current as? NSLocale let code = currentLocale?.iso639_2LanguageCode() 
-one
source share

All Articles