我想知道swift package如何进行本地化。我看了WWDC20/10169视频 - Swift packages: Resources and localization。我正在尝试在自己的项目中做同样的事情。
如果我按照视频中的配置,将.environment(\.locale, Locale(identifier: "es"))
添加到View
预览中,它可以正常工作(但仅在测试sp中)。
当我尝试在实际应用程序中使用本地化资源时,问题就出现了。 过程非常简单 - 我只需在应用程序内部使用来自软件包的本地化字符串的视图。 为了测试目的,我使用特定的语言环境启动我的应用程序(方案设置) - 结果,我总是得到en
翻译。
我的清单:
let package = Package(
name: "MyLibrary",
defaultLocalization: "en",
platforms: [
.iOS(.v14),
],
products: [
.library(
name: "MyLibrary",
targets: ["MyLibrary"]),
],
dependencies: [
],
targets: [
.target(
name: "MyLibrary",
dependencies: [],
path: "Sources"
),
.testTarget(
name: "MyLibraryTests",
dependencies: ["MyLibrary"]),
]
)
包的结构:
resource_bundle_accessor
已经生成成功 - 所以我可以访问 Bundle.module
,并且我也可以按预期列出所有本地化文本 - en
和 es
。
我还将支持的语言添加到了项目本身中:
这是一个快速的演示:
为了生成本地化字符串,我想使用 SwiftGen:
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let format = BundleToken.bundle.localizedString(forKey: key, value: nil, table: table)
return String(format: format, locale: Locale.current, arguments: args)
}
}
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: BundleToken.self)
#endif
}()
}
// swiftlint:enable convenience_type
另外,我进行了测试。
let text = NSLocalizedString("welcome", tableName: "Localizable", bundle: .module, value: "", comment: "")
从Bundle
的Bundle.module.localizedString
方法和SwiftUI
的Text("welcome", bundle: .module)
中获取的结果相同,但不会更改语言,我始终得到开发语言 - en
。
我还可以确认,该构建包含本地化(在lib包中的testLocalization.app内):
我的问题是 - 我做错了什么?错误在哪里?