Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Vapor: How to read a JSON file?

Tags:

swift

vapor

I'm using Vapor, the server-side Swift 4 framework for creating web servers. I have a migration that I'd like to apply that reads in from a JSON file; however, most if not all Swift tutorials I see on this indicate using Bundle, which to my knowledge, isn't available when developing server-side swift applications, which means attempts like this don't work:

if let path = Bundle.main.url(forResource: "myFile", withExtension: "json") {
...

This begs the question, given a relative file path, how can I read in a file using server-side Swift?

like image 611
marked-down Avatar asked Aug 11 '18 03:08

marked-down


1 Answers

Silly me. Vapor exposes a DirectoryConfig object from which you can retrieve the working directory of the application. To parse a file, it thus becomes:

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)
}
like image 162
marked-down Avatar answered Sep 28 '22 09:09

marked-down