How to force NSLocalizedString to use a specific language How to force NSLocalizedString to use a specific language ios ios

How to force NSLocalizedString to use a specific language


NSLocalizedString() (and variants thereof) access the "AppleLanguages" key in NSUserDefaults to determine what the user's settings for preferred languages are. This returns an array of language codes, with the first one being the one set by the user for their phone, and the subsequent ones used as fallbacks if a resource is not available in the preferred language. (on the desktop, the user can specify multiple languages with a custom ordering in System Preferences)

You can override the global setting for your own application if you wish by using the setObject:forKey: method to set your own language list. This will take precedence over the globally set value and be returned to any code in your application that is performing localization. The code for this would look something like:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"];[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate

This would make German the preferred language for your application, with English and French as fallbacks. You would want to call this sometime early in your application's startup. You can read more about language/locale preferences here: Internationalization Programming Topics: Getting the Current Language and Locale


I had the same problem recently and I didn't want to start and patch my entire NSLocalizedString nor force the app to restart for the new language to work. I wanted everything to work as-is.

My solution was to dynamically change the main bundle's class and load the appropriate bundle there:

Header file

@interface NSBundle (Language)+(void)setLanguage:(NSString*)language;@end

Implementation

#import <objc/runtime.h>static const char _bundle=0;@interface BundleEx : NSBundle@end@implementation BundleEx-(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName{    NSBundle* bundle=objc_getAssociatedObject(self, &_bundle);    return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];}@end@implementation NSBundle (Language)+(void)setLanguage:(NSString*)language{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^    {        object_setClass([NSBundle mainBundle],[BundleEx class]);    });    objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}@end

So basically, when your app starts and before you load your first controller, simply call:

[NSBundle setLanguage:@"en"];

When your user changes his preferred language in your setting screen, simply call it again:

[NSBundle setLanguage:@"fr"];

To reset back to system defaults, simply pass nil:

[NSBundle setLanguage:nil];

Enjoy...

For those who need a Swift version:

var bundleKey: UInt8 = 0class AnyLanguageBundle: Bundle {    override func localizedString(forKey key: String,                                  value: String?,                                  table tableName: String?) -> String {        guard let path = objc_getAssociatedObject(self, &bundleKey) as? String,              let bundle = Bundle(path: path) else {            return super.localizedString(forKey: key, value: value, table: tableName)            }        return bundle.localizedString(forKey: key, value: value, table: tableName)    }}extension Bundle {    class func setLanguage(_ language: String) {        defer {            object_setClass(Bundle.main, AnyLanguageBundle.self)        }        objc_setAssociatedObject(Bundle.main, &bundleKey,    Bundle.main.path(forResource: language, ofType: "lproj"), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)    }}


I usually do this in this way, but you MUST have all localization files in your project.

@implementation Languagestatic NSBundle *bundle = nil;+(void)initialize {    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];    NSArray* languages = [defs objectForKey:@"AppleLanguages"];    NSString *current = [[languages objectAtIndex:0] retain];    [self setLanguage:current];}/*  example calls:    [Language setLanguage:@"it"];    [Language setLanguage:@"de"];*/+(void)setLanguage:(NSString *)l{    NSLog(@"preferredLang: %@", l);    NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];    bundle = [[NSBundle bundleWithPath:path] retain];}+(NSString *)get:(NSString *)key alter:(NSString *)alternate {    return [bundle localizedStringForKey:key value:alternate table:nil];}@end