0

Is there a way of getting the localized string for a particular locale, other than the current locale?

Something like a reverse lookup, i.e. I have the localized value, I want to get to the base localized version or even the key.

myLocalizedString.getLocalizedString( locale : NSLocale )

I am well aware of the fact that this isn't super clean, but I don't need explanations as to why it's not a good idea. I'm just in a situation where it seems the least bad.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Frank R.
  • 2,328
  • 1
  • 24
  • 44
  • 1
    Possible duplicate of [How to force NSLocalizedString to use a specific language](https://stackoverflow.com/questions/1669645/how-to-force-nslocalizedstring-to-use-a-specific-language) – Roman Podymov Jul 24 '19 at 09:45

2 Answers2

1

You can simply call this method by sending language code & key string.

func localizestring(for languageCode : String , keyString : String) -> String {
    //language code like --> en/ef/da
    let path = Bundle.main.path(forResource: languageCode, ofType: "lproj")
    let bundle = Bundle(path: path!)
    return NSLocalizedString(keyString , tableName: nil, bundle: bundle!, value: "", comment: "")
}
komara
  • 334
  • 1
  • 7
1

I solved this by extending String with this method in Swift. You can get localized string for any locale you have in your app this way.

extension String {
    func localized(forLanguageCode lanCode: String) -> String {
        guard
            let bundlePath = Bundle.main.path(forResource: lanCode, ofType: "lproj"),
            let bundle = Bundle(path: bundlePath)
        else { return "" }
        
        return NSLocalizedString(
            self,
            bundle: bundle,
            value: " ",
            comment: ""
        )
    }
}

Example (get localized string for ukrainian language when system language is english):

"settings_choose_language".localized(forLanguageCode: "uk")