简体   繁体   中英

Load localized string from my app inside a static lib?

I have a project divided in layers, and the bottom one is included in the top one as a static lib.

The thing is that I need to localize a string in the static lib, using the translations present in my app (upper layer).

Is this possible somehow?

The way I managed to do this is loading the strings from a bundle instead of using NSLocalizedString :

+ (NSString *)getTranslationFromAppBundleForString:(NSString *)originalText {

    NSString * lang = [[NSLocale preferredLanguages] objectAtIndex:0];
    NSString * bundlePath = [[NSBundle mainBundle] pathForResource:lang ofType:@"lproj"];
    NSBundle * bundle = [NSBundle bundleWithPath:bundlePath];

    return [bundle localizedStringForKey:originalText value:originalText table:nil];
}

You can create an LanguageAgent in your static library, add a bundle ressource in that library. Then use a function like this to get localizedString. In my application, I separate language by different table (see picture below for a table named 'Dictionaire'. You can have more than 1 table in your languages bundle.

-(NSString*) myLocalizedStringForKey:(NSString*) key ofTable:(NSString*)tableName {
    //I save selected language in my NSUserDefaults.
    NSString *selectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];

    if (selectedLanguage == nil) {
        [[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"DefaultLanguage"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        selectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
     }

    NSString *langBundleNew = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/langs/Languages.bundle/%@.lproj/",selectedLanguage]; //use your path to the Languages.bundle here. 

    if ([[NSFileManager defaultManager] fileExistsAtPath:langBundleNew]) {
        NSBundle *aBundle = (NSBundle*)[self.dictLangueBundle objectForKey:selectedLanguage];
         NSString* str=[aBundle localizedStringForKey:key value:@"[string not defined]" table:tableName];
         return str;
    } else {
        return @"[]";
    }
}

My language bundle is similar like this: ('Dictionaire' = name of the table)

在此处输入图片说明

Here is a sample of content in my Dictionnaire.strings for 'en.lproj':

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM