20

In my previous framework, I have a localizable.strings file with some global entries for localization. On the left lane, there was a “Localize” button in Xcode to do this.

How can I do this with Swift Package Manager?

TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • [fanton](https://stackoverflow.com/users/666019/fanton) posted an [Answer](https://stackoverflow.com/a/65708230) saying "Here is very exact article about localizing package resources: https://developer.apple.com/documentation/swift_packages/localizing_package_resources" – Scratte Jan 14 '21 at 13:09

2 Answers2

38

To add localizable string file in SPM, it is possible from swift-tools-version: 5.3,

Changes in Package.swift, Needs to set defaultLocalization: "en" then add resources filed in target like,

enter image description here

And package structure should be like,

enter image description here

And to access localizable string through code in the package,

enter image description here

chirag
  • 1,090
  • 9
  • 13
  • 2
    `.module` doesn't work for me. I get the error: `Type 'Bundle' has no member 'module'` – Chanchal Raj Aug 24 '21 at 03:38
  • This only works for me when building and running from terminal with `swift run`, building this in Xcode results in the above error – amq Jan 03 '22 at 20:14
  • 1
    In addition, if you want to use SwiftUI's `LocalizedStringKey()`, you'd use it like `Text(LocalizedStringKey("TITLE"), bundle: .module)`. – Manabu Nakazawa Aug 06 '22 at 11:28
  • If you're using TextField you can't use bundle on it (Manabu's suggestion). So, the only way left is to use NSLocalizedString, and use bundle: .module on that. The accepted answer is solving the issue. – MGY Oct 18 '22 at 07:04
-1

SPM supports resources since 5.3. Check the accepted answer, and this checklist if you still have trouble.


(outdated)

Here are a couple of provisional workarounds that may fit some use cases.

If your framework is distributed only with an app, you can move the localization resources to the app and reference them through its bundle.

  1. Add the Localization.strings file in the app with bundle id my.app.bundle.

  2. Write this from your framework:

    let bundle = Bundle(identifier: "my.app.bundle")!
    NSLocalizedString("SomeKey", tableName: "Localization", bundle: bundle, value: "SomeKey", comment: "")

You can do something similar with images.

Another option is to store your resources in the framework as source code. This requires encoding, for instance, to Base64, then decoding to access the resources. Base64 uses more space, but this may not be an issue depending on your case.

Jano
  • 62,815
  • 21
  • 164
  • 192