Swift包管理器本地化

我想知道本地化如何与 swift 包一起使用。我看到了 WWDC20/10169 视频 - Swift 包:资源和本地化。我正在尝试在我自己的项目中做同样的事情。

如果我做相同的配置(如在 WWDC 视频上)并添加.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,实际上我可以按预期列出所有本地化 -enes.

我还在项目本身中添加了支持的语言:

这是一个快速演示:

为了生成本地化字符串,我想使用 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: "")

或类似的 from Bundle-Bundle.module.localizedString方法和 from SwiftUI Text("welcome", bundle: .module)

结果相同 - 它不会改变语言 - 我总是得到开发语言 - en

我也可以确认,该构建包含本地化(在 lib 包中的 testLocalization.app 内):

这是项目的链接。

所以我的问题 - 我做错了什么?错误在哪里?

以上是Swift包管理器本地化的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>