Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find path to localized directory?

I need to distribute a directory containing html files and images with my app.

The app has support for different languages. I have created a directory for each language and then pick the right one based on current locale:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" 
                                                 ofType:@"html" 
                                            inDirectory:[language stringByAppendingPathExtension:@"html"];];

if (![[NSFileManager defaultManager] fileExistsAtPath:path])
{
    // Fallback to english
    path = [[NSBundle mainBundle] pathForResource:@"index" 
                                           ofType:@"html" 
                                      inDirectory:@"en.html"];
}

How can I better deal with this instead of having to do the above (which is a bit messy)?

I'm thinking perhaps using the xx.lproj directories for this somehow and putting a localized html directory in each xx.lproj directory and use NSBundle pathForResource to find the correct file. Couldn't get it to work though.

like image 663
Martin Wickman Avatar asked May 04 '11 08:05

Martin Wickman


2 Answers

Using the xx.lproj folders with [NSBundle pathForResource:ofType:] is straight-forward.

You can add index.html to your Xcode's project file and then make it localizable from its "Get Info" window. Add another language like "de", and Xcode will copy index.html into the newly created de.lproj. If you remove that file, the app will fall back on the English version.

You can test it with logging:

NSLog([[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]);
like image 142
bdunagan Avatar answered Sep 29 '22 01:09

bdunagan


I too am unable to get this to work:

    NSLog([[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]);

But this does, using the standard Xcode language.lproj structure (e.g., en.lproj):

    NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" 
                  ofType:@"html" 
                  inDirectory:[language stringByAppendingPathExtension:@"lproj"]];

also removed extra ; in Martin's original question above ...

like image 26
Ken Pletzer Avatar answered Sep 29 '22 00:09

Ken Pletzer