How to find the path to a localized directory?

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

The application supports different languages. I created a directory for each language, and then select the correct one based on the current language version:

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 deal with this better instead of doing the above (which is a bit messy)?

I think it’s possible, using directories xx.lprojfor this somehow and putting a localized html directory in each xx.lproj directory and using NSBundle pathForResourceto find the correct file. Failed to get it to work.

+5
source share
5 answers

xx.lproj [NSBundle pathForResource:ofType:] .

index.html Xcode " ". , "de", Xcode index.html de.lproj. , .

:

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

:

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

, Xcode language.lproj(, en.lproj):

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

; ...

+3

: , , pathForResource .

+3

Why not the way forLocalization:

        htmlFile = [[NSBundle mainBundle] pathForResource:@"myContent"
                                               ofType:@"html"
                                          inDirectory:@"de.lproj"
                                      forLocalization:@"de"];

This works fine here with Xcode 5.1.1 and iOS 7.1

Add a generalization to @Martin Wickman (with a digression) and everything should be great.

+1
source

You can use this:

NSString *filename = [NSString stringWithFormat:@"html_%@.html", NSLocalizedString(@"abbr", @"")];
0
source

All Articles