"localizedStringWithFormat" change the language without restarting the app

264 Views Asked by At

I successfully implemented plural localization in my app. But if I change the app language, localizedStringWithFormat still returns the plural in previous language.

If I restart the app, the plural will be returned in correct language (the language that I chose).

Is there any possibility to make it clear for localizedStringWithFormat, in which language it should return the plural?

Example code, where the plural is called:

let candiesEaten: Int = 38
let candyCounterString: String = String.localizedStringWithFormat(NSLocalizedString("TEXT_CANDY_COUNTER", comment: ""), arguments: candiesEaten)

The language is changed in the app like this and it works with all other strings as charm:

private static func setLanguageAndSynchronize(_ lang: [String]) {
        UserDefaults.standard.set(lang, forKey: Preferences.appleLanguagesKey)
        UserDefaults.standard.synchronize()
    }
1

There are 1 best solutions below

0
On

String extension

extension String {
  var localized: String {
    guard let path = Bundle.main.path(forResource: AppLanguageService.shared.getAppLanguage()?.rawValue, ofType: "lproj"),
          let bundle = Bundle(path: path) else { return "" }
    return bundle.localizedString(forKey: self, value: nil, table: nil)
  }
    
  func localizeWithFormat(arguments: CVarArg...) -> String {
     return String(format: self.localized, arguments: arguments)
  }
}

Usage example

let formatedString = "TEXT_CANDY_COUNTER".localizeWithFormat(arguments: candiesEaten)

How to use NSLocalizedString function with variables in Swift?