I'm writing an iOS app which download some statistics from our company server. In case of error the APIs provides an error code and an error description. I would like to keep the error description (which is always in english) for the internal log and to map the error codes to some localised strings. Which would be the best approach for solving this problem? I was thinking of executing a mapping using a .plist file,but not 100% sure.

有帮助吗?

解决方案

Using a plist file with an NSDictionary is fine, as long as the memory footprint is low. I've done something similar.

However, also be aware of the standard method which is NSLocalizedString and using .Strings files for each language.

Here's an example of how to use NSLocalizedString:

// Set the label using the localized string
self.label.text = NSLocalizedString(@"Select choice:", @"Prompt to make a selection.");

The first part is the key, which you define in the file Localizable.strings. If no entry exists in the strings file, then the key name is used, so I make the key equal the default text. In the example above, if no entry is found for the default language, it will just use the key name, which is @"Select choice:".

Then, you create a Localizable.string file and press the Localize button, then create one for each language. Your spanish one might look like this:

/* Contents of Localizable.strings */
"Select choice:" = "Selecciona la opción:";

Of course, you could have an English one, which would look like this:

/* Contents of Localizable.strings */
"Select choice:" = "Select choice:";

The second parameter to NSLocalizedString() is a comment, which is optional, but Apple provides tools to find all of the NSLocalizedString() entries in your code and generate lines in your Strings resource files for you, complete with the comment.

其他提示

I'll add that if your API takes a language parameter and returns messages in that language, you can use its available languages like this (Objective C):

NSArray *availableLanguages = @[@"en", @"es"]; // API's available languages
NSString *preferredLanguage = [NSBundle preferredLocalizationsFromArray:availableLanguages].firstObject;

Then pass preferredLanguage to the API.

(The API might even have a call to get available languages that it supports.)

See https://developer.apple.com/library/content/technotes/tn2418/_index.html

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