Julien Fouilhé
Julien Fouilhé

Reputation: 2658

Translate language code with Xcode 6.1 using NSLocale

Since the last update, I can't translate the language code (en, fr, etc...) into their respective names (English, French, etc...).

It works on a real device, but not in the emulator. It was working using former versions of Xcode. I'm aware that it's written in the release notes that [NSLocale currentLocale] may return en_US in some situations, but that doesn't explain why they are no more "translated". I use this code:

NSString* lang = @"en";
NSLog(@"%@",
    [[NSLocale currentLocale]
        displayNameForKey:NSLocaleIdentifier
        value:lang]
);

which displays (null), instead of English.

The problem is that my app is crashing at some places because of that so I would like to know if there's a workaround.

The weird thing is that the following example, given by Apple, works really well.

NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
NSString *displayNameString = [frLocale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"];
NSLog(@"displayNameString fr_FR: %@", displayNameString);
displayNameString = [frLocale displayNameForKey:NSLocaleIdentifier value:@"en_US"];
NSLog(@"displayNameString en_US: %@", displayNameString);

Upvotes: 2

Views: 864

Answers (2)

Zorayr
Zorayr

Reputation: 24962

This is a known Apple issue for iOS 8.1 simulator only - not reproducible on 8.1 devices. See below issue description from Xcode 6.1 release notes:

Localization and Keyboard settings (including 3rd party keyboards) are not correctly honored by Safari, Maps, and developer apps in the iOS 8.1 Simulator. [NSLocale currentLocale] returns en_US and only the English and Emoji keyboards are available. (18418630, 18512161).

See Xcode 6.1 Release Notes for more details.

Upvotes: 0

gabbler
gabbler

Reputation: 13766

From Xcode release note

In some situations, [NSLocale currentLocale] may return en_US instead of the chosen locale in the iOS 8.1 simulator. (18512161)

+ (NSLocale *)autoupdatingCurrentLocale NS_AVAILABLE(10_5, 2_0); // generally you should use this method

+ (NSLocale *)currentLocale;    // an object representing the user's current locale

A workaround is to use the first one. Using objectForKey on currentLocal instance works.

NSString* lang = @"en_US";
NSLocale *currentLocal = [NSLocale autoupdatingCurrentLocale];
//get the localeIdentifier and create a new NSLocale.
id localIdentifier = [currentLocal objectForKey:NSLocaleIdentifier];
NSLocale *theLocal = [NSLocale localeWithLocaleIdentifier:localIdentifier];
NSLog(@"%@",[theLocal displayNameForKey:NSLocaleIdentifier
                                                  value:lang]
      );

Upvotes: 2

Related Questions