How do I get current application locale?
There may be an easier way than this (see other answers), but this one is most robust, and as long as the general principle of localizing an app through a strings
-file doesn't get obsoleted, this method will work.
Generally, you don't need to get the application locale (but read on, it's possible!) If you want localized text, you use NSLocalizedString()
. If you need to localize images you use localized resources, and so on. However, there are reasons that I can think of which would make it nice to get the "application locale", as you call it: for example for analytics (you want to know in which language your app is used), or for providing a consistent one-language interface to the user if you use server-based communication (e.g. to localize the server error messages in the same language that the user is seeing inside the app.)
If you want to get the localization of the app that is currently visible, I suppose you have a Localizable.strings
file for each supported locale. So, in the Englisch strings-file you can add the line
"lang" = "en";
and in the French string-file you add the line
"lang" = "fr";
then, you can always get the application-locale by calling NSLocalizedString("lang")
(swift) or NSLocalizedString(@"lang")
(objective-C). And of course, whenever you add a new localization to your app, you have to set a "lang" entry into the new localizations strings-file.
The selected answer returns the current device language, but not the actual language used in the app. If you don't provide a localization for the preferred language in your app:
NSString *language = NSBundle.mainBundle.preferredLocalizations.firstObject;
NSLocale *locale = NSLocale.currentLocale;
NSString *countryCode = [locale objectForKey:NSLocaleCountryCode];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString *country = [usLocale displayNameForKey:NSLocaleCountryCode
value:countryCode];
NSLog(@"country: %@", country);