如何在Swift Package Manager中添加资源

SE-0271 by Anders Bertelrud and Ankit Aggarwal brings Resources to Swift Package Manager. If you have any iOS development experience, you’ll know that you can add non-compiled files with Bundle. In the new Swift Package Manager, based on Swift 5.3 or newer, you can add the same thing. You can add images, sound, and JSON and Swift will generate the bundle for you.

Anders BertelrudAnkit Aggarwal的 SE-0271将资源带到了Swift Package Manager。 如果您有任何iOS开发经验,就会知道可以使用Bundle添加未编译的文件。 在基于Swift 5.3或更高版本的新Swift包管理器中,您可以添加相同的内容。 您可以添加图像,声音,并且JSON和Swift将为您生成捆绑包。

At the time of writing, Swift 5.3 isn’t officially released, but if you want to try it, download a snapshot build at Swift Snapshot.

在撰写本文时,Swift 5.3尚未正式发布,但是如果您想尝试,请从Swift Snapshot下载快照版本。

On each target, know that you can declare recursively or specifically what resources you want to add — more details on this later.

在每个目标上,您都可以递归声明,也可以明确声明要添加的资源-稍后将对此进行详细说明。

.target(name: "HelloWorldProgram", dependencies: [], resources: nil)

If you add a non-compiled file to your target directory, Swift will give you this warning:

如果您将未编译的文件添加到目标目录,Swift将向您发出以下警告:

error: found 2 file(s) which are unhandled; explicitly declare them as resources or exclude from the target
/Users/wendyliga/resource-spm/Sources/resource-spm/README.md
/Users/wendyliga/resource-spm/Sources/resource-spm/Images/image.png

To solve this, Swift 5.3 introduces resources parameters on .target. There are two resources you can define.

为了解决这个问题,Swift 5.3在.target上引入了资源参数。 您可以定义两种资源。

复制 (Copy)

copy will ask Swift to apply copy rule to each resource you declare. If you’re targeting directory with copy, then Swift will retain its structure. So, you only want to use copy if you wish to retain its directory structure. If not, use process instead.

copy将要求Swift将复制规则应用于您声明的每个资源。 如果您使用copy来定位目录,则Swift将保留其结构。 因此,仅在希望保留其目录结构的情况下才想使用copy 。 如果没有,请改用process

.copy(path:)

Example:

例:

.target(
name: "HelloWorldProgram",
dependencies: [],
resources: [.copy("README.md"), .copy("image.png")]
)

Example on directory:

目录示例:

.target(
name: "HelloWorldProgram",
dependencies: [],
resources: [.copy(Images), .copy("README.md")]
)

If you check the compiled bundle (it depends on your configuration but the default will be at project-path/.build/build/your-project-name.bundle), you can see Swift will copy and retain its structure.

如果您检查编译的包(取决于您的配置,但默认值将位于project-path/.build/build/your-project-name.bundle ),则可以看到Swift将复制并保留其结构。

Image for post
Copy a Directory Example
复制目录示例

处理 (Process)

process will do almost the same with copy(path:), but instead, just copying the file, process will follow copying and optimizing rules based on the platform it runs on. If you’re targeting a directory, it will recursively add the files inside, but not retain the directory structure.

processcopy(path:)几乎一样,但是,仅复制文件, process将根据其运行的平台遵循复制和优化规则。 如果您要定位目录,它将以递归方式将文件添加到其中,但不会保留目录结构。

.process(path:)

Example:

例:

.target(
name: "HelloWorldProgram",
dependencies: [],
resources: [.process("README.md"), .process("image.png")]
)

Example on directory:

目录示例:

.target(
name: "HelloWorldProgram",
dependencies: [],
resources: [.copy(Images), .copy("README.md")]
)
Image for post
Process a Directory Example
处理目录示例

By default, you should use process. process is preferred because Swift will add platform efficiency rules based on the file type. But what if you want to add localized resources where the Bundle API is currently supported? We’ll discuss this at the end of this article.

默认情况下,您应该使用process 。 首选process ,因为Swift会根据文件类型添加平台效率规则 。 但是,如果要添加当前支持Bundle API的本地化资源怎么办? 我们将在本文结尾处对此进行讨论。

如何使用资源 (How to Use the Resource)

Swift will create boilerplate code for you to easily access resources through Bundle.

Swift将为您创建样板代码,以便您通过Bundle轻松访问资源。

extension Bundle {
/// The bundle associated with the current Swift module.
static let module: Bundle = { ... }()
}

Example:

例:

import Foundationlet picture = Bundle.module.path(forResource: "image", ofType: "png")print(picture) // Optional("/Users/wendyliga/resource-spm/.build/x86_64-apple-macosx/debug/resource-spm_resource-spm.bundle/image.png")

本地化资源 (Localized Resources)

Thanks to David Hart with SE-0278, Swift 5.3 will support localized resources for Swift Package Manager.

感谢David Hart使用SE-0278 ,Swift 5.3将支持Swift Package Manager的本地化资源。

let package = Package(
name: "resource-spm",
defaultLocalization: "en",
...
)

You should add defaultLocalization to your package init to tell Swift that your package will support localization. defaultLocalization will also be used by Swift as the fallback if any localized resources don’t have precise localization.

您应该将defaultLocalization添加到您的package初始化中,以告知Swift您的程序包将支持本地化。 如果任何本地化资源没有精确的本地化,Swift也将defaultLocalization用作后备。

Then create your localized resource by creating a language-tag.lproj directory whose language-tag will be based on the IETF Language Tag (learn more at CFBundleDevelopmentRegion documentation).

然后,通过创建一个language-tag.lproj目录创建本地化资源,该目录的语言标签将基于IETF语言标签 (有关更多信息,请参阅CFBundleDevelopmentRegion文档 )。

Image for post
Localized Resource Example
本地化资源示例

On Package.swift, I add the resources directory declaration:

Package.swift ,我添加资源目录声明:

.process("Resources")

In my example, I will create several localizations: en (English) as default, es (Spanish), id (Indonesia), and fr-CH(French (Switzerland), as IETF language tags.

在我的示例中,我将创建几个本地化:默认为en (英语), es (西班牙语), id (印度尼西亚)和fr-CH (法语(瑞士))作为IETF语言标记。

Also as I mentioned previously, you should use .process even in localization context(localization use case must force you to create a directory and it should retain its structure when compiled to bundle). Swift will do its magic to make this happen even without .copy .

同样如前所述,即使在本地化上下文中也应使用.process (本地化用例必须强制您创建目录,并且在编译为捆绑包时应保留其结构)。 即使没有.copy Swift也会尽其所能使之实现。

Each file will have a hello_tag localized string, for example, France:

每个文件都有一个hello_tag本地化字符串,例如France:

"hello_world" = "Bonjour le monde";

Then you can call this with:

然后,您可以使用以下命令进行调用:

NSLocalizedString("hello_world", bundle: .module, comment: "")

By default, the code above will search for hello_world on available localized strings.

默认情况下,以上代码将在可用的本地化字符串上搜索hello_world

You can do the same thing with other file types, like images, sound, or JSON, by putting each file on its respective localized directory, the same as the Localizable.strings example.

您可以对其他文件类型执行相同的操作, 通过将每个文件放在其各自的本地化目录中(例如Localizable.strings示例),例如图像,声音或JSON。

如果我想强制访问本地化资源怎么办? (What if I Want to Access Localized Resource Forcibly?)

If, for example, you want to access other language resources that are not the current default language on the client, you can access the respective language bundle.

例如,如果要访问客户端上不是当前默认语言的其他语言资源,则可以访问相应的语言包。

Here’s a little bit of a function helper:

这是一个函数助手:

/// source: https://github.com/apple/swift-package-manager/pull/2535/files#diff-cc8e61e90b098f4e9ebc74503408eaa8func localizationBundle(forLanguage language: String) -> Bundle? {
if let path = Bundle.module.path(forResource: language, ofType: "lproj") {
return Bundle(path: path)
} else {
return nil
}
}if let indonesiaBundle = localizationBundle(forLanguage: "id") {
print(NSLocalizedString("hello_world", bundle: indonesiaBundle, comment: "")) // access image
let image = UIImage(named: "MyIcon", in: indonesiaBundle, compatibleWith: UITraitCollection(userInterfaceStyle: .dark))}

示例项目 (Example Project)

WWDC会议 (WWDC Session)

There’s WWDC 2020 session that talks about new Resource on Swift Package Manager, give it a visit

WWDC 2020会议讨论了Swift Package Manager上的新资源,请访问

包装东西 (Wrapping Things Up)

So, are you excited about this new Swift package manager?

那么,您对这个新的Swift软件包管理器感到兴奋吗?

Before Swift 5.3, this meant many Swift package manager libraries or executables that want to include other files outside the Swift file, they need to use the xcodeproj format. But that issue is no more — now you can add resources to your SPM project.

在Swift 5.3之前,这意味着许多Swift包管理器库或可执行文件想要包含Swift文件之外的其他文件,它们需要使用xcodeproj格式。 但这不再是问题-现在您可以将资源添加到SPM项目中。

You can now add native localization support, bring JSON file or audio files into your SPM project.

现在,您可以添加本机本地化支持,将JSON文件或音频文件引入SPM项目。

That’s it from me. Thanks for your time, see you in the next article!

是我的。 感谢您的宝贵时间,在下一篇文章中见!

翻译自: https://medium.com/better-programming/how-to-add-resources-in-swift-package-manager-c437d44ec593

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值