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.
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"]);
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With