Home > Software engineering >  How to override the user language inside the app?
How to override the user language inside the app?

Time:11-19

I am trying to change the language inside my app based on what the user decides. I have tried the following with no luck and was wondering if someone could help point me in the right direction?

UserDefaults.standard.set(["fr"], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()

And then lastly I tried the following, but also had no luck with this either:

    enum Language: String, CaseIterable {
        case japanese, russian, spanish, english
        var code: String {
            switch self {
            case .japanese: return "ja"
            case .russian: return "ru"
            case .spanish: return "es"
            case .english: return "en"
            }
        }

        static var selected: Language {
            set {
                UserDefaults.standard.set([newValue.code], forKey: "AppleLanguages")
                UserDefaults.standard.set(newValue.rawValue, forKey: "language")
            }
            get {
                return Language(rawValue: UserDefaults.standard.string(forKey: "language") ?? "") ?? .english

            }
        }
    }

Calling it with:

Language.selected = .russian

Any help would be much appreciated. Cheers.

CodePudding user response:

You have to use localizable strings, kindly check the following link: Swift App localization

CodePudding user response:

I was able to figure it out by removing the object value first before setting it. That enabled me to get the language to change in the app. Thanks everyone. Solution:

NSUserDefaults.standardUserDefaults().removeObjectForKey("AppleLanguages")
NSUserDefaults.standardUserDefaults().setObject(["de"], forKey: "AppleLanguages"   
NSUserDefaults.standardUserDefaults().synchronize()
  • Related