Xcode 6.1 iOS 8.1中,NSLocale displayNameForKey NSLocaleIdentifier返回为空。该问题涉及IT技术。

17
这段代码是用于通过国家/地区码获取对应的国家/地区名称,但是如果传入的国家/地区码无效,就会返回 nil。因此,可能需要检查一下传入的国家/地区码是否正确。

技术问题: http://stackoverflow.com/questions/26603766/swift-nslocale-simulator-ios-8 - Alexandr Semeniuk
1
这个问题只是模拟器的问题。我今天在设备上测试了它,我得到了正确的国家名称。 - Yuriy Bosov
刚在模拟器上遇到了这个问题 - 我用一个包含所有国家列表的表格视图进行填充,在模拟器上由于displayNameForKey返回null而崩溃了。我已经在所有8.1模拟器设备上尝试过,它们都会崩溃。带有iOS 7.1的iPhone4和iPhone5模拟器运行良好。我的代码在安装了8.1的物理设备iPhone4s和iPhone5上也可以正常运行,所以我猜这只是Xcode的一个bug。解决方案 - 在苹果修复之前,在设备上进行测试 - 这很麻烦,因为我手头没有6和6 Plus。 - SimonTheDiver
5个回答

20

这是一个针对iOS 8.1模拟器的已知Apple问题,而在8.1设备上不能重现。请参见Xcode 6.1版本说明中以下问题描述:

iOS 8.1模拟器在Safari、地图和开发人员应用程序中无法正确遵守本地化和键盘设置(包括第三方键盘)。[NSLocale currentLocale] 返回 en_US,并且只有英语和表情键盘可用。(18418630, 18512161)。

欲了解更多详情,请查看Xcode 6.1版本说明


7
请尝试下面的代码,应该可以工作。我在我的设备和模拟器8.1上都试过了。
- (NSString *)countryNameByCode:(NSString*)countryCode {
  return [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
}

1
这对我有效。
NSLocale *currentLocale = [[NSLocale alloc] initWithLocaleIdentifier:[NSLocale currentLocale].localeIdentifier];

 for (AVSpeechSynthesisVoice *voice in [AVSpeechSynthesisVoice speechVoices]) {
            NSString *languageLocalised = [currentLocale displayNameForKey:NSLocaleIdentifier value:voice.language];
            NSLog(@"%@ displayNameForKey %@: %@", currentLocale.localeIdentifier, voice.language, languageLocalised);
 }

注意:你的第一行代码包含了冗余的内容。你可以将其简化为 NSLocale *currentLocale = [NSLocale currentLocale]; - JonEasy

0
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

0
- (NSString *)countryNameByCode:(NSString*)countryCode 
{
    NSString *identifier = [[NSLocale preferredLanguages] firstObject];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:identifier];
    NSString *countryName = [locale displayNameForKey:NSLocaleIdentifier value:countryCode];
    return countryName;
}

我不明白为什么在iOS 8[[NSLocale currentLocale] displayNameForKey...]不能返回国家名称,但是上面的代码应该可以解决你的问题。


显然,它返回的是语言名称(法语、德语等),而不是国家。 - Arnaud
2
是的,我的端上也不工作...对于国家代码“US”,我得到一个标识符“_US”,导致国家名称为空。 - Zorayr
解决方案已经可用,你只需要使用 NSLocaleCountryCode 而不是 NSLocaleIdentifier - HiveHicks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接