Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

xcode - iOS base internationalization: change the language at runtime

We know this is an old and painful question.

If you don't know - let me briefly describe the problem. Suppose we have an application and we want to use xcode built-in localization using NSLocalizedString() - the standard way recommended by Apple. All good until you want to change the language at runtime. There is no way that you can force the application to use another language, Apple recommends always use the system language, or manually load and manage the resources (of course we don't want to do that).

From here you have very few alternatives.

1) User Default

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", nil] forKey:@"AppleLanguages"];

This key is undocumented however it's allowed to do so. The problem with this method is that the the language will be set only after the application restart. Unfortunately you cannot restart the app by yourself, you will have to ask the user to do so.

2) Use some custom macros as in this example. The problem with this method is that - you will have to adapt all your codebase - storyboards and nib files wont be translated - the localization wont work in general because genstring utility that XCode uses recognize only NSLocalizedStringXXX macros or you will end up in running manually genstring with some post-build step.

3) Solution that I tried to implement, by tweaking inside NSBundle. The idea is that you override the method localizedStringForKey on the instance of NSBundle object, and then call this method on a different bundle with a different language. Sample usage:

#import "BundleLocalization.h"
...
[[BundleLocalization sharedInstance] setLanguage:@"fr"];

or

[BundleLocalization sharedInstance].language = @"de";
NSLog(@"Application language: %@", [BundleLocalization sharedInstance].language);

It works, simple and elegant fully compatible with all types of resources. The code can be found here.

Please can someone comment on the legal aspect of this approach with regards to Apple Policy?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...