Oftentimes we deal with cryptic language abbreviations, such as en-GB or de-DE. While it’s more or less clear to us humans what this means, it would be nice to have a way to display something more readable to our users.
We can do this with a method from the NSLocale object. Consider this snippet:
NSString *code = @"en-GB"; NSLocale *locale = [NSLocale currentLocale]; NSString *translation = [locale displayNameForKey:NSLocaleIdentifier value:code]; NSLog(@"%@ is %@", code, translation); // output: en-GB is English (United Kingdom)
Here we translate en-GB into “English (United Kingdom)”. First we take the current device’s locale, then we use the displayNameForKey method to turn the ISO language code into a human readable description.
The beauty is that no matter what language the device is set to, iOS will display the translation in the matching locale. For example, on a German device, en-GB would be translated into “English (Vereinigtes Königreich)”. Even though Germans would probably never refer to the UK as that. But I digress.
This also works with abbreviated language codes, such as “en” (instead of en-GB). In that case, the output is simply “English” without the country identifier.
We can also force iOS to display the translation in a locale of our choice. Rather than using the currently selected locale on the device, we can pick one and display the output accordingly:
NSString *code = @"en-GB"; NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"fr-FR"]; NSString *translation = [locale displayNameForKey:NSLocaleIdentifier value:code]; NSLog(@"%@ is %@", code, translation); // output: en-GB is anglais (Royaume-Uni)