Reputation: 327
The application that I'm working on supports 3 languages: English, French and German.
How I can get the current application language (NOT the device language)?
The problem is that I have to get the current language of the application in order to send it with a request to the server and the respond should be in the right language. The device language is useless because if the user switch the os language to Italian, the app is running in English and I need to send english to the server.
Thanks
Upvotes: 25
Views: 10560
Reputation: 117
Since iOS 13 the language can be set for each app individually.
In the session "Creating Great Localized Experiences with Xcode 11" at WWDC19 they showed two options for determining the user settings for the application.
Get the currently running application language:
Bundle.main.preferredLocalizations.first
Get the best language, given an external language code list:
let availableLanguages = Server.requestLanguages()
Bundle.preferredLocalizations(from: availableLanguages).first
Upvotes: 6
Reputation: 841
The accepted answer is a workaround.
Regarding language preferences in the device itself, you have the
[NSLocale preferredLanguages]
which will give you an ordered array of the preferred languages as defined in the system's General Settings.
The Cocoa Touch framework will take this list of preferred languages into account when loading the app's localization resources and filter it according to the translations you provide in the bundle.
This filtered and ordered list of localized languages can be obtained with
[[NSBundle mainBundle] preferredLocalizations]
Your server requests should match the first value in this array or you will have a language mismatch between app and server data.
Upvotes: 49
Reputation: 119
You may use the preferredLocalizations method of the NSBundle class:
NSString *currentLocalization = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
Upvotes: 14
Reputation: 6160
The app language will change when the user change the device language and you can get it from the NSUserDefaults
(i will show you how if you want to ) unless there are an option to change the language inside the app then you can easy save the current used language and send it to the server when ever you want.
Upvotes: -2
Reputation: 10005
What i always do:
Add a string entry into the Localizable.strings files.
I always use the key "lang"="de";
(or "lang"="en"
, etc.).
Then you can use it in your NSURLRequest by adding the language over NSLocalizedString(@"lang", @"")
With that method you have absolute control what is going to be sent to you backend.
Upvotes: 46