Manually get specific localized string - ios

Let say I already put everything on Localizable.strings for several language. As for now I use NSLocalizedString and it return the text based on [[NSUserDefaults standardUserDefaults] objectForKey:#"AppleLanguages"] setting. Now I need to get specific string for each language.
Let say I want to put it on select language setting and show it when user press Submit button. So it will show a dialog with a message "Select this language?" on respective language that user select.

You can get any translation from any language file by loading it manually:
- (NSString *)localizedString:(NSString *)string forCountry:(NSString *)countryCode {
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"Localizable" ofType:#"strings" inDirectory:nil forLocalization:countryCode];
NSBundle *dataBundle = [[NSBundle alloc] initWithPath:[bundlePath stringByDeletingLastPathComponent]];
return NSLocalizedStringFromTableInBundle(string, #"Localizable", dataBundle, nil); }
Does this help?

Related

Localizing ios App

I have a working ios app in my hand. My company wants me to provide a "Translate" button in the app that would make it Arabic. Can I do this with iOS Localisation? The app is live in app store and I have to start with Localisation work now
You can access to localization strings in specific language, but in this case you need to implement your own function instead of NSLocalizedString. Here is an example:
NSString *Localized(NSString *key) {
static NSBundle *localizationBundle = nil;
static dispatch_once_t onceToken1;
dispatch_once(&onceToken1, ^
{
NSString *languageCode = [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]; //The language code you need
localizationBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:languageCode ofType:#"lproj"]];
});
NSString *string = [localizationBundle localizedStringForKey:key value:nil table:nil];
return string; }
Just reload localizationBundle every time user switches language by translate button

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':

iOS Strings Localization Get Base Value

I am looking to get the base value or english value for a localized string from a .string file. I am showing the user in the view controller the localized string but my function uses the base value or english value. I have searched everywhere but I cannot find a solution for this.
It depends on how you show your localized string. If you are using something as below you can update code:
-(NSString *)languageSelectedStringForKey:(NSString *) key showKey: (BOOL) show
{
NSString *language = [[NSString alloc] init]
if (!show)
language = [[NSUserDefaults standardUserDefaults] stringForKey:#"Language"];
else
return key;
NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:#"lproj"];
if ( !path )
return NSLocalizedString(key, nil);
return [[NSBundle bundleWithPath:path] localizedStringForKey:(key) value: #"" table:nil];
}
So where you need, you can show only key (your base value)..

Localized resources in ios static library

I followed this Tutorial to use resources in my ios static library.
Now, I can use images, xib files, plist files... into my static library but I can't use localized resources..
In my bundle resources I can see all (for example) images into correct folders (es: english image into en.lproj folder)
But .. when I load the image, I see always the english image also when my language device is different from english.
I have same problem about localized strings: always I see only english localized strings.
* EDIT **
I could not find a better solution for this problem ..
I was in a hurry to fix this so I duvuto apply this method to solve the problem with the localized images:
+ (NSString*) getLocalizedPathImageWithImageName:(NSString*) aImageName
{
NSString *currentDeviceLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *resourceBundlePath = [[NSBundle mainBundle] pathForResource:BUNDLE_RESOURCESNAME ofType:#"bundle"];
NSString *completeLocalizedImageName = [aImageName stringByAppendingFormat:#"_%#",currentDeviceLanguage];
NSString *imagePath = [[NSBundle bundleWithPath:resourceBundlePath] pathForResource:completeLocalizedImageName ofType:USERBUTTON_PNG_FILEEXTENSION];
if (imagePath == nil) {
completeLocalizedImageName = [aImageName stringByAppendingFormat:#"_%#",DEFAULT_LANGUAGE];
imagePath = [[NSBundle bundleWithPath:resourceBundlePath] pathForResource:completeLocalizedImageName ofType:USERBUTTON_PNG_FILEEXTENSION];
}
return imagePath;
}
a better solution is welcome

iOS: How to Get the Device Current Language Setting?

There are some features within my application that are supposed to be based on the language settings of the device where it's running.
I want to get the actual language and not some country settings. Foe example, if the language is English, I don't care if it's US, UK, Australia, etc...
I'm familiar with the NSLocale object, but it seems to relate to the Region Format setting and not to the Language setting (see screen shot below) so when I try to retrieve the language out of it using [locale displayNameForKey:NSLocaleIdentifier value:[locale localeIdentifier] I get things like English (United States) instead of English; also, I think that what I need is the Language data and not the Region Format (am I right?).
Can anyone direct me to how to retrieve the language setting?
User preferred languages are stored can be retrieved from locale as array and current language identifier is the first object in that array:
NSString *currentLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
If you want language in more readable form then use displayNameForKey:value: method of NSLocale:
NSString *langID = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *lang = [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:langID];
Try this:
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSArray* arrayLanguages = [userDefaults objectForKey:#"AppleLanguages"];
NSString* currentLanguage = [arrayLanguages objectAtIndex:0];
Getting language and region in Swift:
LF.log("language", NSLocale.preferredLanguages())
LF.log("locale", NSBundle.mainBundle().preferredLocalizations)
In my case I'm getting:
language: '(
"zh-Hans"
)'
locale: '(
en
)'
In Swift 4:
let currentLanguage = Locale.current.languageCode
It will give you just the language code, no country code.
Swift:
let language = NSBundle.mainBundle().preferredLocalizations[0] as NSString
Working solution:
let language = NSLocale.preferredLanguages()[0]
let languageDic = NSLocale.componentsFromLocaleIdentifier(language) as NSDictionary
//let countryCode = languageDic.objectForKey("kCFLocaleCountryCodeKey")
let languageCode = languageDic.objectForKey("kCFLocaleLanguageCodeKey") as! String
print(languageCode)
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
Find the solution in XCode's helper document, it wrote:
Getting the Current Language
To get the language that the app is using from the main application bundle, use the preferredLocalizations method in the NSBundle class:
NSString *languageID = [[NSBundle mainBundle] preferredLocalizations].firstObject;
Use below code to fetch Localised language without having trouble to the en-india, en-us etc..
NSString *Ph = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
In and After ios9 this code need to take in cosideration
To know the current language selected within your localizations use
[[NSBundle mainBundle] preferredLocalizations]
Example:
NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
To get two letter word
NSString *language = [[[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0] substringToIndex:2];
Swift:
let language = NSBundle.mainBundle().preferredLocalizations.first as NSString

Resources