Force NSLocalizedString use special language with Swift

With quick as I can get my application to read data from a specific Localizable.strings.

I put this in doneFinishLaunchingWithOptions before creating an instance of the ViewController, but it still shows me the application in English.

NSUserDefaults.standardUserDefaults().removeObjectForKey("AppleLanguages") NSUserDefaults.standardUserDefaults().setObject("fr", forKey: "AppleLanguages" NSUserDefaults.standardUserDefaults().synchronize() 

And I tried passing Array for the AppleLanguages ​​key this way, but it still doesn't work:

 NSUserDefaults.standardUserDefaults().setObject(["fr"], forKey: "AppleLanguages" 

And as soon as this is done, can I call it inside the application and accept the changes in the review without restarting the application?

+6
source share
3 answers

You cannot immediately change the application language by changing the value of AppleLanguages . This requires a restart of the application before the change takes effect.

It seems that your problem is accessing localization strings in different languages, and not changing the application language, right? If you want your application to support multiple languages, you can simply provide translations and rely on settings.app for the actual change.

If you want to access localization strings other than the current localization used, you need to access the correct set of translations. And then just request this package for translations. The following code snippet should do the trick.

 let language = "en" let path = NSBundle.mainBundle().pathForResource(language, ofType: "lproj") let bundle = NSBundle(path: path!) let string = bundle?.localizedStringForKey("key", value: nil, table: nil) 
+24
source

@Radu I also did this for XCUITests thanks to @Markus original answer:

You can explicitly indicate the path to your MainBundle, it will only work on your Mac using Simulator, but it is often used on continuous integration platforms, so this may be acceptable:

 let app = XCUIApplication() let language:String? = "en" let path = "/Users/{username}/{path_to_your_project}/\(language).lproj" let bundle = NSBundle(path: path) let string = bundle?.localizedStringForKey("key", value: nil, table: nil) 
+1
source

With NSLocalizedString you can specify a kit.

 let language = "fr" let path = Bundle.main.path(forResource: language, ofType: "lproj")! let bundle = Bundle(path: path)! let localizedString = NSLocalizedString(key, bundle: bundle, comment: "") 

Or with the kit, you can also directly call localizedStringForKey:value:table:

0
source

Source: https://habr.com/ru/post/980806/


All Articles