一个 Vapor 4 库,用于使用 libqrencode 创建 QR 码图像文件。
QREncode 使用 Swift Package Manager 来管理其代码依赖项。为了在您的代码库中使用 QREncode,建议您也这样做。在您自己的 Package.swift 依赖项中添加对该软件包的依赖项。
在您的 Package.swift
文件中添加以下内容
dependencies: [
.package(url: "https://github.com/garanda21/vapor-qrencode.git", branch: "main"),
],
然后为您要使用的每个 QREncode 目标添加目标依赖项。
targets: [
.target(name: "MyApp", dependencies: [
.product(name: "QREncode", package: "vapor-qrencode")
]),
]
)
首先,安装 libqrencode。 该库已在 4.1.1 版本上进行过测试。在 QREncode
初始化程序中指定 qrencode
的位置。 默认值为 /usr/bin/qrencode
。运行它以确保它及其任何依赖项已正确安装。
首先,安装 homebrew,然后在您的终端输入以下命令
brew install qrencode
输入以下命令
apt-get update
apt-get install qrencode
要创建一个 QR 码,创建并配置一个 QREncode
,然后调用 generateQR(on: threadPool, eventLoop: eventLoop)
。这是一个使用 Vapor 的完整示例
import QREncode
func qr(_ req: Request) async throws -> Response {
//Make sure to initialice using the correct path for qrencode
let qrencode = QREncode(text: "Test", fileName: "testfile.png", size: .large ,path: "/opt/homebrew/bin/qrencode")
if let data = try await qrencode.generateQR(on: req.application.threadPool, eventLoop: req.eventLoop)
{
FileManager.default.createFile(atPath: "/tmp/vapor-qrencode/testOutput.png", contents: data, attributes: nil)
print("Test output QR image can be viewed at /tmp/vapor-qrencode/testOutput.png")
return Response(
status: .ok,
headers: HTTPHeaders([("Content-Type", "image/png")]),
body: .init(data: data)
)
}
else
{
return Response(
status: .ok,
headers: HTTPHeaders([("Content-Type", "text/plain")]),
body: "No data"
)
}
}