开发者

Localization: How to get the current user language?

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 URLW开发者_StackOverflow中文版ithString:@"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! )


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]];


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜