Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Get localized version of a string for a specific language

I'm building an application for iOS that will be available in both English and French languages. I've read some tutorials around internationalization and I have an understanding of how it works and what I need to do.

The problem I'm having is there is a specific case where I want to load French strings for an English user.

I understand it's possible to set the language for the entire application, but that it requires the application to be restarted before it will take affect. I'd like to avoid this, and instead be able to pick to load French or English strings on demand.

Is it possible to load strings from a .strings file for a specific language programmatically?

like image 314
raydowe Avatar asked Feb 20 '15 17:02

raydowe


People also ask

How do you force NSLocalizedString to use a specific language?

struct CustomLanguage { func createBundlePath () -> Bundle { let selectedLanguage = //recover the language chosen by the user (in my case, from UserDefaults) let path = Bundle. main. path(forResource: selectedLanguage, ofType: "lproj") return Bundle(path: path!) ! } }

How do I localize a string in Swift?

string file, select it and on the File Inspector (right menu) select “Localize”. Select your the new language you added and click on “Finish”. If you select the file again you should see something similar to the first image below (be sure to select both the supported languages).

What is a localizable string?

Localizable. strings stores application strings as key-value pairs for each language. Let's create this file for the base language first. Select File → New → File… or just tap Ctrl+N or Cmd+N .

How do you make a string file localizable?

Let us move on to create a string file called 'Localizable' that will hold the text we want to localize. Choose File → New → File ..., select Strings File under Resources, and click Next. Name it Localizable, then click on Create.


1 Answers

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")
like image 82
Dmytro Yashchenko Avatar answered Nov 10 '22 19:11

Dmytro Yashchenko