[英]Swift Vapor: How to read a JSON file?
我正在使用Vapor,服務器端Swift 4框架來創建Web服務器。 我有一個我想申請的遷移,它從JSON文件中讀取; 但是,大多數(如果不是全部)我在這上面看到的Swift教程都表明使用了Bundle
,據我所知,在開發服務器端swift應用程序時它不可用,這意味着這樣的嘗試不起作用:
if let path = Bundle.main.url(forResource: "myFile", withExtension: "json") {
...
這引出了一個問題,給定一個相對文件路徑,如何使用服務器端Swift讀取文件?
傻我。 Vapor公開DirectoryConfig
對象,您可以從中檢索應用程序的工作目錄。 要解析文件,它將變為:
let directory = DirectoryConfig.detect()
let configDir = "Sources/App/Configuration"
do {
let data = try Data(contentsOf: URL(fileURLWithPath: directory.workDir)
.appendingPathComponent(configDir, isDirectory: true)
.appendingPathComponent("myFile.json", isDirectory: false))
// continue processing
} catch {
print(error)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.