iPhone/iOS:如何在我的应用程序本地化的所有语言中获取本地化字符串列表?

Tat*_*eva 16 iphone localization nslocalizedstring ios

我需要向服务器发送特定字符串的本地化列表.

这意味着,如果我的应用程序有一个字符串Foo,其本地化为英语为@"Foo",俄语为@"Фу",我想向服务器发送如下列表:

  • String Foo:
    • 英语:"Foo"
    • 俄语:"Фу"

我认为我需要做的是:

  1. 枚举我的应用程序本地化的每种语言的本地化字符串
  2. 获取每种语言的本地化版本的Foo

我该怎么做(1)我该怎么做(2)?

bdu*_*gan 33

您可以通过将English.lproj/Localizable.strings作为字典读取并获取其键来检索所有字符串键:

NSString *stringsPath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:stringsPath];
Run Code Online (Sandbox Code Playgroud)

要获得每种语言的翻译,您可以迭代每个英语键的语言并使用NSLocalizedStringFromTableInBundle:

for (NSString *language in [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"]) {
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]];
    NSLog(@"%@: %@", language, NSLocalizedStringFromTableInBundle(@"Testing", @"Localizable", bundle, nil));
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,上面代码示例中对`pathForResource`的第一次调用将返回*current*本地化的路径,不一定是英语的路径(例如,如果您的模拟器/设备设置为德语,您将获得`de的路径.LPROJ/Localizable.strings`). (2认同)