I have an iOS project that is localized into 16 languages. Only some words are not localized (Mainly those that go into an update and the localization office did not deliver in time). For my keys I do not use the english wording, as this can also change if a translator wishes. So now if I just don't have a translation for a language, if falls back to the key that I used. But as this key is not 'human readable' or at least not 'human enjoyable to read' this is a problem.

I did some research but couldn't find a solution to my exact problem. I have fe.:

Localizable.strings in en.lproj
@"Key1" = @"Value 1"
@"Key2" = @"Value 2"

Localizable.strings in de.lproj
@"Key1" = @"Wert 1"
// Note that @"Key2" is missing here in my de.lproj

I would expect that if I make NSLocalizedString(@"Key2", ...)
and am running on a german phone, it falls back to the english
translation for this key as it exists...

So for now i just copied the english translation into the missing Localizable.strings files. But this is a big hack! But also using the english words as keys seems to be a hack to me!

Is there any way to tell my app, that it should use f.e. english as the fallback if there is no value for a given key? I tried adding a base localization but this doesn't help...

Thanks a lot

有帮助吗?

解决方案

As far as I know, there's no "official" way to do it, but I have implemented functions such as this before:

NSString * L(NSString * translation_key) {
    NSString * s = NSLocalizedString(translation_key, nil);
    if (![[[NSLocale preferredLanguages] objectAtIndex:0] isEqualToString:@"en"] && [s isEqualToString:translation_key]) {
        NSString * path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
        NSBundle * languageBundle = [NSBundle bundleWithPath:path];
        s = [languageBundle localizedStringForKey:translation_key value:@"" table:nil];
    }
    return s;
}

borrowed from: https://stackoverflow.com/a/8784451/1403046

Basically, instead of NSLocalizedString(), which will return the input string, this version will fallback to English if necessary.

其他提示

Inspired by this and this, my Swift code version:

public func LS(_ key: String) -> String {
    let value = NSLocalizedString(key, comment: "")
    if value != key || NSLocale.preferredLanguages.first == "en" {
        return value
    }

    // Fall back to en
    guard
        let path = Bundle.main.path(forResource: "en", ofType: "lproj"),
        let bundle = Bundle(path: path)
        else { return value }
    return NSLocalizedString(key, bundle: bundle, comment: "")
}

Many developers expect an incomplete translation to fallback on the development language.. but that's not the way Apple choose to behave. I have a pseudocode to help better understand how Apple choose to fallback.

You can use a Base localization and all unlocalized strings will be taken from this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top