4

Is it possible to retrieve strings for a specific locale programmatically regardless of what locale the phone is set to? For example, users may be running the phone in English, but I want to retrieve French strings instead without changing the OS locale setting.

Note: This is not a duplicate of the above question. I do not want to override the current setting within my app, I merely want to have the ability to retrieve language values of whatever locale I wish programatically. My app contents may be displaying English text, but I want a specific component of my app to display a different language instead.

Boon
  • 40,656
  • 60
  • 209
  • 315
  • Retrieve strings from what? Where? – Sergey Grischyov Apr 01 '14 at 21:18
  • Check out a talk called **Hidden iOS 7 Development Gems** https://developer.apple.com/tech-talks/videos/ the final part of it talks about what you need. – Sergey Grischyov Apr 01 '14 at 21:26
  • 1
    possible duplicate of [How to force NSLocalizedString to use a specific language](http://stackoverflow.com/questions/1669645/how-to-force-nslocalizedstring-to-use-a-specific-language) – lootsch Apr 01 '14 at 21:48
  • 1
    It's not a duplicate. I don't want to set AppleLanguages. The app can still be using English, but I want to retrieve a different language programatically. – Boon Apr 01 '14 at 21:55
  • @SergiusGee Watched the video, didn't have the info I am looking for. Thank you for pointing me to it. – Boon Apr 01 '14 at 21:55
  • @Boon Have you seen this question: http://stackoverflow.com/questions/13785455/multiple-localized-strings-files-in-ios-app-bundle – lootsch Apr 01 '14 at 22:04
  • Take a look at http://stackoverflow.com/questions/3153600/iphone-reading-from-localizable-strings-file-as-a-key-value-in-a-dictionary it explains how to do what you're looking for. – David Berry Apr 01 '14 at 22:27
  • @David Please list your answer below. I will accept it. – Boon Apr 02 '14 at 01:21
  • @lootsch Thanks for the link, even though it's not what I am looking for, it's still very useful. – Boon Apr 02 '14 at 01:22
  • 1
    @Boon no need, since it's just a duplicate question response. – David Berry Apr 02 '14 at 15:06

1 Answers1

1

I solved this by extending String with this method. 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")