0

I have a problem when I change the application language using swift code. In my case I had to use the xliff file that was automatically generated from the storyboard/xib. My code:

let APPLE_LANGUAGE_KEY = "AppleLanguages"
/// L102Language
class L102Language {
    /// get current Apple language
    class func currentAppleLanguage() -> String{
        let userdef = UserDefaults.standard
        let langArray = userdef.object(forKey: APPLE_LANGUAGE_KEY) as! NSArray
        let current = langArray.firstObject as! String
        return current
    }
    /// set @lang to be the first in Applelanguages list
    class func setAppleLAnguageTo(lang: String) {
        let userdef = UserDefaults.standard
        userdef.set([lang,currentAppleLanguage()], forKey: APPLE_LANGUAGE_KEY)
        userdef.synchronize()
        
    }
}

Use:

if L102Language.currentAppleLanguage() == "en" {
    L102Language.setAppleLAnguageTo(lang: "vi")
    UIView.appearance().semanticContentAttribute = .forceRightToLeft
} else {
    L102Language.setAppleLAnguageTo(lang: "en")
    UIView.appearance().semanticContentAttribute = .forceLeftToRight
}

After userdef.synchronize() is executed the application does not change the language. It only really works when I restart the app. I think this way is not good. In this case, what else do I need to do to change the language of the application without restarting. thanks everyone

Update: I resolved problem with answer https://stackoverflow.com/a/48187049/12429634 Thanks everyone!

  • Keep in mind that `synchronize()` *is unnecessary and shouldn't be used*. Ref: https://developer.apple.com/documentation/foundation/userdefaults/1414005-synchronize – Eric Aya Apr 11 '22 at 16:05

1 Answers1

1

You will need to register for the NSLocale currentLocaleDidChangeNotification, and write code to update your UI when you get notified.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thank you for support. I resolved problem with answer https://stackoverflow.com/a/48187049/12429634 – Phạm Đông Apr 11 '22 at 15:35
  • Oh, I misunderstood your question. I thought you were asking how to respond to the user changing languages in settings while your app was running. I see now that you were asking how to let the user change languages from within the app. You might want to also implement the currentLocaleDidChangeNotification so you handle it properly if the user changes languages from settings. – Duncan C Apr 11 '22 at 17:19