Boon
Boon

Reputation: 41470

iOS: How to retrieve locale strings for a specific locale than what the user has set in OS?

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.

Upvotes: 4

Views: 1219

Answers (1)

Dmytro Yashchenko
Dmytro Yashchenko

Reputation: 931

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

Upvotes: 0

Related Questions