Search code examples
iosobjective-cnslocale

How to detect correctly language user of device objective-c?


I have a query about iOS. I want to detect language of my device, for change any texts in my app if language is english and other if isn't english. But when I detect language, always detect region and not detect language. In others words if I go to change language, this don't change. If I change region, language changes.

My code is:

 NSString *userLocale = [[NSLocale currentLocale] localeIdentifier];
NSString *userLanguage = [userLocale substringToIndex:2];
NSLog(@"%@", userLanguage); // return format "en", "es"... (english or spanish)

Could be that this problem appear because with [NSLocale currentLocale] get en_Us and this parameters depends of region?

Thanks!


Solution

  • If you want the language try

    [NSLocale preferredLanguages];
    

    It will return an array of the user's language preference and the most preferred language will be the first in the list.

    NSLocale encapsulates a lot more than just the current language. Things like currency identifier and what to use for the decimal separator are just a few. A Spanish speaking user in the northwestern United States may want to see things in Spanish but would probably still expect to see the $ for currency.

    With that said I suspect what your really looking for is full fledged localization support in which case there is tons of information out there on how to localize your app. The macro

    NSLocalizedString 
    

    and its siblings allow you to write language agnostic code (for the most part).