你有没有遇到过 SPM 不支持资源的问题?你是如何将模板、演示文件以及其他一些东西从子模块导入到你的应用程序中的呢?
嗯,我希望 Configure 能让您在处理资源文件时稍微轻松一点。
没有依赖项,因此可以与 Vapor、Perfect、Kitura 等框架一起使用......
注意 该系统主要为 server-side-swift 设计,但在任何 iOS/tvOS 或 macOS 上都能正常编译!
只需将以下行添加到您的 Package.swift
文件中。
.package(url: "https://github.com/LiveUI/Configure.git", .branch("master"))
let resource = BasicWebResource(
resourceUrl: "http://www.example.com/Resources/email-template.leaf",
destinationPath: "Resources/email-template.leaf" // Where to install the file to
)
try ResourcesManager.default.add(resource)
let resource = BasicGithubResource(
organization: "LiveUI",
repository: "YourRepo",
branch: "master",
path: "Resources/email-template.leaf",
destinationPath: "Resources/email-template.leaf" // Where to install the file to
)
try ResourcesManager.default.add(resource)
import Configure
// Create a string resource
let template = """
Hi #(user.firstname) #(user.lastname)
This is an email template for you
Bye,
LiveUI team!
"""
let resource = template.asResource(destination: "Resources/email-template.leaf")
try ResourcesManager.default.add(resource)
当您准备就绪时,运行安装程序
try ResourcesManager.default.run()
有很多便捷方法可以帮助您创建模板,例如之前提到的字符串上的 asResource
。还有用于 URL、URL 数组和字符串的方法。
您还可以通过使用预制的协议非常轻松地创建完全自定义的安装程序,例如这样
public struct ModelResource<T>: Resource where T: Codable {
/// Your model which conforms to Codable
public let model: T
/// Where the final file will be saved
public let destinationPath: String
/// Make the resource to be rewritten every time it runs
public var alwaysOverride: Bool {
return true
}
/// Converting to data
public func data() throws -> Data {
let data = try JSONEncoder().encode(model)
return data
}
/// Intializer
public init(model: T, destinationPath: String) {
self.model = model
self.destinationPath = destinationPath
}
}
此软件包有意不包含任何依赖项,因此,要将资源放入 Vapor 3 的 Resources
文件夹中,一个小技巧是为 Resource 提供一个 destination
,可以像这样设置
extension Request {
/// Gives absolute path URL for the Resources folder
var resourcesUrl: URL {
let config = DirectoryConfig.detect()
var url: URL = URL(fileURLWithPath: config.workDir).appendingPathComponent("Resources")
return url
}
}
加入我们的 Slack,在 #help-boost 频道中... 获得帮助 :)
Boost 的核心软件包,Boost 是一个完全开源的、用 Swift 编写的企业级应用商店!
我们喜欢 PR,多多益善...... 所以如果您有有趣的改进、错误修复或新功能,请随时与我们联系。如果您在开始开发之前对某些事情不确定,您可以随时通过我们的 Slack 联系我们的开发和产品团队。
Ondrej Rafaj (@rafiki270 在 Github, Twitter, LiveUI Slack 和 Vapor Slack 上)
有关更多信息,请参阅 LICENSE 文件。