Search code examples
objective-clocalizationlocalizable.strings

NSLocalizedString using external sources in Objective C?


Is there a way to make the localization or Localizable.strings read from directories outside NSBundle?

I am trying to make my app read localizations from a file that is downloaded via a server, is there a way good way to do this?

Thanks in advance.


Solution

  • You will have to write your own MyLocalizedString function which reads the file manually. A .strings file is actually an old type of property list, so it can be read using the NSPropertyListSerialization class like this:

    id plist = [NSPropertyListSerialization
                   propertyListWithData:[NSData dataWithContentsOfFile:stringsFilePath]
                                options:0
                                 format:NULL
                                  error:&error];
    

    plist is just an NSDictionary, so you can read a string value from the result like this:

    [plist objectForKey:@"my_string"];
    

    You should probably implement some sort of cache so that you aren't parsing the whole file for each string lookup.

    Note that if you are using genstrings and the other related command line tools, you can use the following option to specify the name of your custom lookup function:

    Usage: genstrings [OPTION] file1.[mc] ... filen.[mc]
    
    ...[snip]...
    
    -s substring             substitute 'substring' for NSLocalizedString.
    

    If these strings files are being uploaded to a server, you can improve performance in the app a bit by first converting them to the binary plist format (this is what Xcode would normally do during a build):

    plutil -convert binary1 myStrings.strings