Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLocale NSLocale preferredLanguages is not updating on language change

I am trying to get the current preferred language selected by the user using the following piece of code:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

This is giving me the preferred language as expected for the first time the app is run but the changes are not reflected once I change the language in the system settings. If I uninstall the app, then change the language and then again reinstall the app, the app is now working for this new language (and is only showing this language)

Here's what is happening:

  • The language is set to English (Australian) when the app is first installed.
  • The app will show *language gives the value en-AU (correct value).
  • Now the language is now changed to Serbian.
  • After restarting the app *language is still giving en-AU whereas it should have sr-XX.
  • After re-installing the app, the language is showing the correct value sr-XX and the app is working as expected but now it won't change to any other language (as described)

I am testing the app directly on an iPhone (iOS 11). I have added the localization resources in the project settings and just to be sure I have also set the default application language as System Preferred in scheme.

I also tried to use currentLocale but it is still giving the same result.

I also found the following code somewhere, this also is giving and array 2 elements but is behaving the same as preferredLanguage and not changing with the language change.

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *languages = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:@"AppleLanguages"]];

I am relatively new to iOS dev and not sure where I'm doing it wrong. Please help.


1 Answers

If you want to locale that "always reflects the latest configuration settings", use autoupdatingCurrent in Swift, autoupdatingCurrentLocale in Objective-C.

You might also want to establish yourself as an observer of NSLocale.currentLocaleDidChangeNotification in Swift, NSCurrentLocaleDidChangeNotification in Objective-C, if you want to be notified of any changes if the app happens to be suspending or running in background when the locale changes (in order to, for example, update the UI accordingly).

like image 140
Rob Avatar answered Sep 03 '25 14:09

Rob