Fixed translation bug when the locale contained the region (#765)

* Fixed the issue, added tests and italian translation

* changelog

* improved translation handling code and added more tests

* Update UnitTests/Sources/LocalizationTests.swift

Co-authored-by: Stefan Ceriu <stefanc@matrix.org>

---------

Co-authored-by: Stefan Ceriu <stefanc@matrix.org>
This commit is contained in:
Mauro
2023-04-05 10:36:02 +02:00
committed by GitHub
parent df92eed1a0
commit d24ee73d15
13 changed files with 499 additions and 345 deletions
@@ -78,18 +78,22 @@ extension {{enumName}} {
let languages = Bundle.preferredLanguages
for language in languages {
let translation = trIn(language, table, key, args)
if translation != key {
if let translation = trIn(language, table, key, args) {
return translation
// If we can't find a translation for this language
// we check if we can find one by stripping the region
} else if let langCode = Locale(identifier: language).language.languageCode?.identifier,
let translation = trIn(langCode, table, key, args) {
return translation
}
}
}
return key
}
}
private static func trIn(_ language: String, _ table: String, _ key: String, _ args: CVarArg...) -> String {
private static func trIn(_ language: String, _ table: String, _ key: String, _ args: CVarArg...) -> String? {
guard let bundle = Bundle(for: BundleToken.self).lprojBundle(for: language) else {
// no translations for the desired language
return key
return nil
}
let format = NSLocalizedString(key, tableName: table, bundle: bundle, comment: "")
return String(format: format, locale: Locale(identifier: language), arguments: args)