xcode 6.1 iOS 8.1 NSLocale displayNameForKey NSLocaleIdentifier return nil

陌路散爱 提交于 2019-12-04 16:09:25

问题


- (NSString *)countryNameByCode:(NSString*)countryCode
{
    NSString *identifier = [NSLocale localeIdentifierFromComponents:@{NSLocaleCountryCode: countryCode}];
    NSString *countryName = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:identifier];

    return countryName;
}

This returned nil. Why?


回答1:


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.




回答2:


Please try below code, it should work. I tried it on my device as well as simulator 8.1

- (NSString *)countryNameByCode:(NSString*)countryCode {
  return [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
}



回答3:


This works for me

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);
 }



回答4:


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

I don't understand why [[NSLocale currentLocale] displayNameForKey...] doesn't return country name in iOS 8 but the code above should resolve your problem.




回答5:


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


来源:https://stackoverflow.com/questions/26613011/xcode-6-1-ios-8-1-nslocale-displaynameforkey-nslocaleidentifier-return-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!