17

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:

  • String Foo:
    • English: "Foo"
    • Russian: "Фу"

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

  1. Enumerate localized strings for each language my app is localized for
  2. Get the localized version of Foo for each language

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

Tatiana Racheva
  • 1,289
  • 1
  • 13
  • 31
  • Have you peeked at `NSLocalizedStringFromTable`? http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html%23//apple_ref/c/macro/NSLocalizedStringFromTableInBundle – joshpaul Jun 10 '11 at 18:55
  • 1
    From table seems to be a way to compartmentalize your strings, as opposed to keeping them all in one default table. This is not what I want. I want to get all the different localizations of a particular string. – Tatiana Racheva Jun 12 '11 at 20:12

1 Answers1

37

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

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:

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));
}
bdunagan
  • 1,202
  • 12
  • 15
  • This sounds reasonable; the other options I saw required rewriting the way we retrieve strings, but this is way less invasive and looks like it does what I need. I'll try it today. – Tatiana Racheva Jun 24 '11 at 16:39
  • 2
    Note that the first call to `pathForResource` in the code samples above will return the path for the *current* localisation, not necessarily the english one (e.g. if your simulator/device is set to german, you will get the path to `de.lproj/Localizable.strings`). – Alessandro Mar 29 '13 at 12:24