Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`NSLocale preferredLanguages` contains "-US" since iOS 9

Tags:

ios

ios9

We have code like the following to retrieved the user language preference:

NSString *language = [[NSLocale preferredLanguages] firstObject];

Before iOS 8.4, language is "zh-Hans", "de", "ru", "ja" and etc. But since iOS 9, I notice that there is additional three characters "-US" appended to language. For example, "zh-Hans" becomes "zh-Hans-US"

I can find any documentation about this change. I assume that I could do something like the following to workaround this issue.

NSRange range = [language rangeOfString:@"-US"];
if (range.location!=NSNotFound && language.length==range.location+3) {
    // If the last 3 chars are "-US", remove it
    language = [language substringToIndex:range.location];
}

However, I am not sure whether it is safe to do so. It seems that "-US" is the location where the user is using the app? But this doesn't really make sense because we are in Canada. Has any body from other part of the world tried this?

like image 217
Yuchen Avatar asked Mar 15 '23 13:03

Yuchen


2 Answers

Apple has started adding regions onto the language locales in iOS 9. Per Apple's docs, it has a fallback mechanism now if no region is specified. If you need to only support some languages, here is how I worked around it, per Apple's docs suggestion:

NSArray<NSString *> *availableLanguages = @[@"en", @"es", @"de", @"ru", @"zh-Hans", @"ja", @"pt"];
self.currentLanguage = [[[NSBundle preferredLocalizationsFromArray:availableLanguages] firstObject] mutableCopy];

This will automatically assign one of the languages in the array based off the User's language settings without having to worry about regions.

Source: Technical Note TN2418

like image 178
Bill L Avatar answered Mar 17 '23 06:03

Bill L


To extract the region I think this is a better solution:

// Format is Lang - Region
NSString *fullString = [[NSLocale preferredLanguages] firstObject];
NSMutableArray *langAndRegion = [NSMutableArray arrayWithArray:[fullString componentsSeparatedByString:@"-"]];

// Region is the last item
NSString *region = [langAndRegion objectAtIndex:langAndRegion.count - 1];

// We remove region
[langAndRegion removeLastObject];

// We recreate array with the lang
NSString *lang = [langAndRegion componentsJoinedByString:@"-"];
like image 40
Beninho85 Avatar answered Mar 17 '23 06:03

Beninho85