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?
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!) ! } }
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).
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 .
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With