Search code examples
iphonelocale

iPhone - Custom language setup


In my application, users can choose a language, so I would like my app to change the language accordingly, but it doesn't work. I have found this code online:

// Force languages
NSString * lang=[[NSUserDefaults standardUserDefaults] stringForKey:@"idioma"];
NSLog(@"language %@",[[NSUserDefaults standardUserDefaults] stringForKey:@"AppleLanguages"]);
if ([lang isEqualToString:@"castella"]) {

    [[NSUserDefaults standardUserDefaults]
     setObject:[NSArray arrayWithObject:@"es"]
     forKey:@"AppleLanguages"];
} //else just default user lang

This code doesn't work. I think I am just setting up another preference setting. I really want to modify the locale. I have some strings that are localized and also some of the NIB files, so I would like to add the Spanish to prefered locales list on the first position, but I don't really understand how to do that.

In the settings for the application, I have an option to chose the language. That is not just out of my stubborness; it is just that regional laguages are important here and sometimes the iPhone doesn't provide support for them, but I pronvide the translations.


From the answers I decided to give up messing with the locale, but would it be possible to show a different NIB file (from en.proj or es.proj)? I already have the first part:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSString * lang=[[NSUserDefaults standardUserDefaults] stringForKey:@"idioma"];

        if ([lang isEqualToString:@"castella"]) {
            //Load NIB filer from "es.proj".
        }
    }
    return self;
}

Is that even possible?


Solution

  • Locale should be set by the user in iPhone settings, I think that if you force this parameter from your app you go out of your sandbox and your app could be rejected.

    Instead, add localizations in your NIB files and/or Localizable.strings in your project. Your app will show the best language for the user automatically.

    If you still want to change the language inside your app, then don't try to change locale setting, but just change what you show on the screen within your app.

    You can save the language you want in [NSUserDefaults standardUserDefaults] and show your labels according to this parameter:

    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"language"] isEqualToString:@"English"]) {
        aLabel.text = @"This is English.";
    } else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"language"] isEqualToString:@"Italian"]) {
        aLabel.text = @"Questo e' italiano.";
    } else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"language"] isEqualToString:@"Japanese"]) {
        aLabel.text = @"これは日本語です。";
    }