Bundle.preferredLocalizations confusion - ios

The 3 preferredLocalizations of Bundle are so confusing that I have so many questions:
Why the 2 preferredLocalizations methods are class methods but keep talking about some unspecified specific bundle as if they are called on some individual Bundle instance?
preferredLocalizations(from:): What exactly are a bundle object and the bundle?
Returns one or more localizations from the specified list that a bundle object would use to locate resources for the current user.
An array of NSString objects, each of which specifies the language ID for a localization that the bundle supports.
preferred​Localizations(from:​for​Preferences:​): What exactly are the specified bundle and the receiver’s bundle?
Returns the localizations that a bundle object would prefer, given the specified bundle and user’s language preferences.
An array of NSString objects, each of which identifies a localization in the receiver’s bundle. These strings are ordered in the array according to the specified preferences and are taken from the strings in the localizations​Array parameter. If none of the user-preferred localizations are available in the bundle, this method returns one of the bundle localizations.
Why preferredLocalizations(from: localizations) does't return the same result as preferred​Localizations(from: localizations, ​for​Preferences:​ nil)? As noted above reading their docs doesn't really help. Sure they look designed this way but actually not:
// Locale.preferredLanguages: ["es-CN", "ja-CN", "zh-Hans-CN", "en-CN", "he-IL"].
let localizations = ["de", "en", "es", "fr", "it"]
print(Bundle.preferredLocalizations(from: localizations)) // ["en"]
print(Bundle.preferredLocalizations(from: localizations, forPreferences: nil)) // ["es"]

The reference documentation isn't that great; Technical Note 2418 explains it better.
Specifically, it says
Note that Bundle.preferredLocalizations(from:) will restrict the results to localizations supported by Bundle.mainBundle(), or the return value of Bundle.mainBundle().localizations(). If you would like to match against a different set of language identifiers, use Bundle.preferredLocalizations(from:forPreferences:) which does not rely on mainBundle’s localizations and instead solely relies on the two arguments passed in.
So,
If you use Bundle.preferredLocalizations(from:), the localizations list you give it is first filtered against the localizations defined for the main bundle (Bundle.main.localizations).
If you use Bundle.preferredLocalizations(from:forPreferences:), it works with the list you give it.
In the example you gave, Bundle.preferredLocalizations(from: localizations) returns ["en"]. This is likely because your app does not have any version of Spanish ("es") defined. If you add a Spanish localization to your project, it should return ["es"], since "es-CN" is listed before "en-CN".

Related

NSLocalizedString is returning the key

In my framework app, I have some localization files added and have a method to get
localised strings as follow
-(NSString *)getCurrentLocale{
return NSLocalizedString(#"mykey", nil);
}
and I have installed this pod into one demo app, and trying to get the locale but it always returns the key, (it returns 'mykey')
I have double checked the format and name (Localizable.strings) within the string files
all files has proper format
but I do have locale strings as values in my Localizable.strings
ex: "mykey" = "ar_SA";
any Idea where I am going wrong?
Usually, this happens when you don't have the Localizable.strings file in the appropriate language folder (e.g. de.lproj). Also, ensure you haven't put your Localizable.strings file in the Base.lproj folder, as the same problem will occur.
To summarize, make sure your project Localizations have their Localizable.strings files in their respective language folders to provide the correct translations.
Finally, if the above are true (and this may be obvious), the device must have its locale set to actually pull strings from a given language.
Reference: Internationalization and Localization Guide

NSLocalizedString - Force country specific string file

We are facing a strange behaviour with the handling of NSLoaclizedString with our bundle strings file.
We have maintained our strings file in:
de_AT (german in Austria)
de_DE (german in Germany)
We didn't setup any base/default strings file since we usually wan't to define per region which strings file should be used. So
Region Poland should use de_DE
Region Italy should use de_AT
During our tests we just recognized that NSLocalizedString just takes the first bundle (de_AT) independant of any Locale if the locale doesn't match.
Is there any way to define/control for which Locale we want to see the translations?
We only found a parameter "tableName" for the language, but no language & country specific locale... we don't want to create Localizable.strings for every available combination of language & country.
Thanks!
Ok we researched a lot, our current solution is to create independant Localizable.strings file and name them per locale:
de_AT.strings
de_DE.strings
Based on our mapping logic we do then set the right bundleName...

Can't get the CFBundleIdentifier from dynamically loaded NSBundle

I'm trying to load a bundle dynamically, to be used in place of the mainBundle in few cases.
I managed to load the bundle with some resources, like Localizable.strings and so on.
And when I use localizedStringForKey against that bundle, the right localized string is loaded. This is to say that it works.
Nevertheless, I'd like to get even have a bundle identifier. Thus, I added to the root of the bundle folder the info.plist file, containing the CFBundleIdentifier string.
This, doesn't work. When I try to get the identifier via
[myBundle bundleIdentifier]
I get a null value. I tried to name the file both as
Info.plist
and
MyBundle-Info.plist
where MyBundle is the name of the bundle (the content is stored in MyBundle.bundle). But no luck.
I really don't get what's wrong. Do I have to set other keys in the info plist? Or maybe it's a naming problem? Any help will be more than appreciated.
I ended up looking at the Core Foundation (after all, NSBundle is based on CFBundle) source code and figured out where was the problem. So..
The function in charge of gathering the info.plist content is CFBundleGetInfoDictionary. This is called anytime an information theoretically contained in the plist is requested.
Looking at CFBundle.c, the implementation of CFBundleGetInfoDictionary checks whether the _infoDict field of the bundle is initialized and in case it's not, it initializes it:
if (!bundle->_infoDict) bundle->_infoDict = _CFBundleCopyInfoDictionaryInDirectoryWithVersion(CFGetAllocator(bundle), bundle->_url, bundle->_version);
By calling that function on my CFBundle I didn't have any luck, so I guessed something wrong must have been happening in _CFBundleCopyInfoDictionaryInDirectoryWithVersion.
Looking at the source code, I noticed that, depending on the bundle->_version, a different path is used to search the info plist. The version in this case depends on the dir structure used to setup the bundle. To be exact, my version was 0, because, as specified in the function _CFBundleURLLooksLikeBundleVersion (used during bundle initialization), bundle with the Resources dir are this:
// check for existence of "Resources" or "Contents" or "Support Files"
// but check for the most likely one first
// version 0: old-style "Resources" bundles
// version 1: obsolete "Support Files" bundles
// version 2: modern "Contents" bundles
// version 3: none of the above (see below)
// version 4: not a bundle (for main bundle only)
So, to finish the story, the base URL of the Info.plist is initialized in _CFBundleCopyInfoDictionaryInDirectoryWithVersion based on the version 0
infoURLFromBase = _CFBundleInfoURLFromBase0;
that is defined as:
#define _CFBundleInfoURLFromBase0 CFSTR("Resources/Info.plist")
Soooo... I've put my Info.plist in the Resources dir and not outside and now it works.
I guess I'm somehow an idiot for having done all this trip, given that this stuff is probably written somewhere in the doc, but I couldn't find it :(

Is there a way to modify the strings used for localization in iOS at runtime?

Is there a way to alter the localization strings after iOS reads them from Localizable.strings, and still maintain the ability use NSLocalizedStringWithDefaultValue(key, table, bundle, value, comment)? In other words, is it possible to programmatically alter localized strings, say, after receiving an updated set of strings from a server?
This question assumes that Localizable.strings can't be modified because that would require modifying the main NSBundle, which is not allowed after an app is installed.
One way would be to create a new bundle containing your desired strings file and use that bundle instead of [NSBundle mainBundle] in NSLocalizedStringWithDefaultValue(...).
Redefine your NSLocalizedString macros to whatever you want:
#undef NSLocalizedString
#define NSLocalizedString(key, comment) \
[MyLocalizationManager localizedStringForKey:key]

Localizing strings from the Settings.bundle using InAppSettingsKit

I am attempting to use InAppSettingsKit to manage my settings. This uses the Settings.bundle with a .plist file and the .strings files for each of the languages being translated.
I can confirm that the translation of my strings is working properly outside of my application, using the Setting application. But when I am in my application, the translation is not occurring.
I think it comes down to code like this, from the InAppSettingsKit class IASKSettingsReader, with a couple logging statements that I thought my be helpful:
- (NSString*)titleForStringId:(NSString*)stringId {
NSLog(#"%#",[_bundle localizedStringForKey:stringId value:stringId table:self.localizationTable]);
NSLog(#"%#",[_bundle localizedInfoDictionary]);
return [_bundle localizedStringForKey:stringId value:stringId table:self.localizationTable];
}
If I understand correctly, this should be using a table with the name self.localizationTable as the source of the translation. This value is simply "Root". It's not a path to the Root.strings file in the selected language, so I am guessing that the method localizedStringForKey:value:table: must be using some global system reference that points to the correct path.
I have confirmed that the strings file name is "Root.strings" all around, with a capital R, including in the Root.plist file.
[_bundle localizedInfoDictionary] returns (null); It is doing this for two language settings of English and French.
I'm not sure how to debug this. Thanks for any help you can give.
I'm using InAppSettingsKit with localized text with no problems. Two things I can think of that you could check: are your Root.strings files located in the correct subdirectories of Settings.bundle (en.lproj and fr.lproj for English and French?
Is there a "Strings Filename" entry in your Root.plist? It should simply contain a string with value "Root"
It has been quite some time since I resolved this, and at the time, I didn't fully understand it. But, in the interest of closing out this question, I'll point to the following documentation for future reference:
NSBundle Class Reference
which refers to the following:
Resource Programming Guide
In the second document, refer to the section "String REsources -> Loading String Resources Into Your Code"
The solution contains a properly configured Root.strings file, which shows up in the file list like this:

Resources