iVentis
iVentis

Reputation: 1153

Manual language with correct NumberFormatter and localizedStringWithFormat

I added a manual language section inside my iOS App where you can change the language the app should be displayed in. If someone chooses to select a manual language I override the "AppleLanguages" standardUserDefaults like so

NSString *language = [[[NSUserDefaults alloc] initWithSuiteName:kAppGroup] objectForKey:kManualLanguageKey];

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

Now when the user restarts the app (after terminating it) the App automatically loads the correct LocalizedStrings.

Now here is my problem:

even though this solves my problem of changing the language of the app it does not display numbers etc. correctly. Number/DateFormatter and localizedStringWithFormat depend on the [NSLocale currentLocale]. I know I could just overrite the current lokale as well like so

[[NSUserDefaults standardUserDefaults] setObject:language
                                                      forKey:@"AppleLocale"];

but then I can't get the real language/region selected in the system settings once the user decides to disable the manual language. I could store the currentLocale inside my own userDefaults before I override it but then if the user decides (for whatever reason) to change the system language while the manual language in the app is active I won't be able to get this new selected system language.

Is there any way to get the right format of Numbers and Dates without manually changing the locale property of NumberFormatter etc.?

Upvotes: 3

Views: 291

Answers (1)

iVentis
iVentis

Reputation: 1153

Ok, I found a way to reset the current locale after the user disables the manual language on http://www.thetawelle.de/?p=3800

In main.m if the bool for manual language is false, I reset the current language like this:

  NSArray *keysToRemove = @[@"AppleLanguages",@"NSLanguages",@"AppleLocale"];
            NSLog( @"RESETTING TO USE SYSTEM LOCALE" );
            @try {
                for( NSString *currentKey in keysToRemove ) {
                    if( [defaults objectForKey:currentKey] ) {
                        [defaults removeObjectForKey:currentKey];
                    }
                }
            }
            @catch (NSException *exception) {
                // NOTHNG TO CATCH HERE
            }
            @finally {
                [defaults synchronize];
            }

after that, the current locale and language are back to the language and region selected in the system settings.

Upvotes: 3

Related Questions