Use iOS localization handling for strings. (#803)

This commit is contained in:
Doug
2023-04-17 15:58:39 +01:00
committed by GitHub
parent 59bbff7a70
commit e333eff731
14 changed files with 59 additions and 130 deletions

View File

@@ -76,17 +76,12 @@ import Foundation
extension {{enumName}} {
static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
// No need to check languages, we always default to en for untranslated strings
guard let bundle = Bundle(for: BundleToken.self).lprojBundle(for: "en") else {
// no translations for the desired language
return key
}
guard let bundle = Bundle.lprojBundle(for: "en") else { return key }
let format = NSLocalizedString(key, tableName: table, bundle: bundle, comment: "")
return String(format: format, locale: Locale(identifier: "en"), arguments: args)
}
}
private final class BundleToken {}
{% else %}
// No string found
{% endif %}

View File

@@ -75,33 +75,26 @@ import Foundation
extension {{enumName}} {
static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let languages = Bundle.preferredLanguages
// Use preferredLocalizations to get a language that is in the bundle and the user's preferred list of languages.
let languages = Bundle.overrideLocalizations ?? Bundle.app.preferredLocalizations
for language in languages {
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
}
return Bundle.app.developmentLocalization.flatMap { trIn($0, table, key, args) } ?? key
}
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 nil
}
guard let bundle = Bundle.lprojBundle(for: language) else { return nil }
let format = NSLocalizedString(key, tableName: table, bundle: bundle, comment: "")
return String(format: format, locale: Locale(identifier: language), arguments: args)
let translation = String(format: format, locale: Locale(identifier: language), arguments: args)
guard translation != key else { return nil }
return translation
}
}
private final class BundleToken {}
{% else %}
// No string found
{% endif %}