Iphone sdk - Get Localized text from specific localized.strings file

5k Views Asked by At

Is it possible to get a localized string from a specific localized.strings file, rather than from the system chosen localized.strings file, ONLY ONE TIME. I do not need to change all the localized texts, only some of them.

What I want to do is to have localized strings defined from language preferences but also localization. So that a user from Brazil location with English lang will get the application in English but some texts will be specific to the region so I want them in Portuguese.

But a user from Argentina, also with iPhone in English will get the application in English but some texts will be in Spanish.

Something like

 NSLocalizedStringFromTable("string.key","pt_BR",nil)

I thought that sending that to the table parameter would work but it didn't as it looks for the name of the file and not for the language.

3

There are 3 best solutions below

1
On

Perhaps you want to use NSBundle's localizedStringForKey:value:table: rather than NSLocalizedString(). This method would give you the opportunity to specify a different table.

[[NSBundle mainBundle] localizedStringForKey:@"stringKey" 
  value:defaultString table:tableName];

BTW, do not forget your @ in front of objective-C strings ;-).

2
On
2
On

You can use the different bundle to choosing specific language:

NSString * path = [[NSBundle mainBundle] pathForResource:@"pt-PT" ofType:@"lproj"];
NSBundle * bundle = nil;
if(path == nil){
    bundle = [NSBundle mainBundle];
}else{
    bundle = [NSBundle bundleWithPath:path];
}
NSString * str = [bundle localizedStringForKey:@"a string" value:@"comment" table:nil];

Swift 3.0:

extension Bundle {
    static let base: Bundle = {
        if let path = Bundle.main.path(forResource: "Base", ofType: "lproj") {
            if let baseBundle = Bundle(path: path) {
                return baseBundle
            }
        }
        return Bundle.main
    }()
}

let localizedStr = Bundle.base.localizedString(forKey: key, value: nil, table: table)