9

I'm about to localize an iPhone application. I want to use a different URL when the user's language (iOS system language) is german.

I want to know if this is the correct way of doing that:

NSURL *url = [NSURL URLWithString:@"http://..."]; // english URL
NSString* languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
if ([languageCode isEqualToString:@"de"]) {
    url = [NSURL URLWithString:@"http://..."]; // german URL
}

I understand that [NSLocale currentLocale] returns the language based on the current region, but not the system language, neither does [NSLocale systemLocale] work.

(I don't want to use NSLocalizedString here! )

Felix
  • 35,354
  • 13
  • 96
  • 143

3 Answers3

13
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];

Your code is OK. But I will doit like this:

    NSString *urlString = nil;
    NSString *languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
    if ([languageCode isEqualToString:@"de"]) {
        urlString = @"http://...";
    }else{
        urlString = @"http://...";
    }
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
Alex Terente
  • 12,006
  • 5
  • 51
  • 71
9

I would just use NSLocalizedString to look up the localized url like this:

NSString* urlString = NSLocalizedString(@"myUrlKey", nil);

Then in your Localizable.strings files you could just do:

// German
"myUrlKey" = "http://www.example.com/de/myapp";

And

// English
"myUrlKey" = "http://www.example.com/en/myapp";

respectively.

Moritz
  • 3,235
  • 26
  • 17
1

Better to use

[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];

if you want to test it with Xcode 6 new feature of testing other language without change the system preference's.

the Reverend
  • 12,305
  • 10
  • 66
  • 121
  • Caution: The current locale is not the same as the preferred language! The locale is what defines how text is compared and how numbers and dates are formatted. The preferred language is the actual language. So, a user (like me) might be using German locale (to get German dates and a 24h clock) but still prefer to use OS X in English. If you want to determine which translations to show, then use the preferred language, not the locale! (Many apps get this wrong, and it's quite annoying when I get an app in German even though I prefer English). – Thomas Tempelmann Jun 09 '16 at 22:55