Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get system locale and system language in cocoa

I want to get the system default language and system locale.

I have tried the following code snippet to get the system current locale as the following

NSLocale *locale;
locale = [NSLocale systemLocale];

NSString * localLanguage = [locale objectForKey:NSLocaleIdentifier];
NSLog (@"Language : %@", localLanguage); 

NSLog(@"System locale Identifier %@",[locale localeIdentifier]);

But nothing is displayed with System locale Identifier.If it is currentlocale it is giving the correct result.Why system locale is not giving any value and how to get system default language not the user preferred language?please help

like image 250
Akbar Avatar asked Jun 08 '12 11:06

Akbar


2 Answers

You can simply use: NSString* language = [[NSLocale preferredLanguages] objectAtIndex:0];

like image 193
user1458963 Avatar answered Nov 11 '22 01:11

user1458963


The default NSLocaleIdentifier is intentionally @"" to indicate that there is no current selection. According to Apple, systemLocale is just a fallback for keys that aren't implemented in the user's selected locale (currentLocale), and since that's always set and it's always under the user's control, it makes sense.

If you want to follow the user's list of preferred languages, you want to use + preferredLanguages, which returns a list of the languages that the user prefers, in the order in which they prefer them. This works for both OSX and iOS, and serves to provide an appropriate fallback for the system when choosing languages.

For testing, you can use the command-line switch -AppleLanguages with a value of a comma-separated, parenthesis-surrounded array (example: (DE,FR,EN)) and Xcode will simulate that being the preferred languages list for the user.

Since the user sets the preferred languages (at least in OSX), the operating system will follow the list when it chooses localized data for the user. Generally, doing anything more than using the macros is considered unnecessary due to this fact. However, you can manually look at the value if you have non-resource information you need to localize.

like image 24
gaige Avatar answered Nov 11 '22 00:11

gaige