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

时间:2021-08-21 12:42:16

I need to send my server a list of localizations for a particular string.

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

Meaning, if my app has a string Foo which is localized as @"Foo" in English and @"Фу" in Russian, I'd like to send the server a list such as this:

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

  • String Foo:
    • English: "Foo"
    • 英语:“Foo”
    • Russian: "Фу"
    • 俄语:“Фу”
  • String Foo:英语:“Foo”俄语:“Фу”

What I think I need to be able to do is:

我认为我需要做的是:

  1. Enumerate localized strings for each language my app is localized for
  2. 为我的应用程序本地化的每种语言枚举本地化字符串
  3. Get the localized version of Foo for each language
  4. 获取每种语言的本地化版本的Foo

How do I do (1) and how do I do (2)?

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

1 个解决方案

#1


32  

You can retrieve all of the string keys by reading in English.lproj/Localizable.strings as a dictionary and fetching its keys:

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

NSString *stringsPath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:stringsPath];

To get each language's translation, you can iterate over the languages for each English key and use NSLocalizedStringFromTableInBundle:

要获取每种语言的翻译,您可以迭代每个英语键的语言并使用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));
}

#1


32  

You can retrieve all of the string keys by reading in English.lproj/Localizable.strings as a dictionary and fetching its keys:

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

NSString *stringsPath = [[NSBundle mainBundle] pathForResource:@"Localizable" ofType:@"strings"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:stringsPath];

To get each language's translation, you can iterate over the languages for each English key and use NSLocalizedStringFromTableInBundle:

要获取每种语言的翻译,您可以迭代每个英语键的语言并使用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));
}