2021年3月21日星期日

Swift package manager localization

I'm wondering, how localization works with the swift package. I saw the WWDC20/10169 video - Swift packages: Resources and localization. I'm trying to do the same things within my own project.

If I do same configuration (as on WWDC video) and add .environment(\.locale, Locale(identifier: "es")) to View preview, it works (but only when test inside sp).

The problems start when I try to use localized resources inside the actual app. The process is very simple - I just use a view with a localized string from the package inside the app. For test purposes I launch my app with a specific locale (scheme settings) - the result, I always get en translation.

My manifest:

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"]),    ]  )  

Structure of the package:

Structure of the package

resource_bundle_accessor is generated fine - so I have an access to Bundle.module, and indeed I can list all localizations as expected - en and es.

I also added supported languages into the project itself:

Supported languages

Here is a quick demo:

demo

For generating localized string I want to use 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)      

没有评论:

发表评论