1

I have a Swift console app where I'm trying to open a simple JSON file that I've included in a bundle for the console app. I'm able to load the bundle and get a path to the file and I've verified in terminal that the path exists. However when I attempt to get the contents I get an error "Error Domain=NSCocoaErrorDomain Code=260 "The file “configuration.json” couldn’t be opened because there is no such file." UserInfo={NSFilePath=file:///Users/myName/Library/Developer/Xcode/DerivedData/JsonConfigurationReader-femnivebllduwxekfipxluxynhbj/Build/Products/Debug/Configuration.bundle/Contents/Resources/configuration.json, NSUnderlyingError=0x10630c080 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}"

I've pretty much followed the instructions of this SO post: Read a file in MacOS Command Tool Project

Here is the code I'm using:

import Foundation
// MARK: - Configuration
struct Configuration: Codable {              //Representation of structure of JSON data
    let developer: String
    
    static func readJsonData(forName name: String) -> Data? {      //Function to read JSON file and return data
        do {
            let currentDirectoryUrl = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
            let bundleUrl = URL(fileURLWithPath: "Configuration.bundle", isDirectory: true, relativeTo: currentDirectoryUrl)
            let bundle = Bundle(url: bundleUrl)
            if let jsonFileURL = bundle?.url(forResource: "configuration", withExtension: "json") {
                let contents = try String(contentsOfFile: jsonFileURL.absoluteString)
//                    let jsonData = json?.data(using: .utf8)
                return nil //jsonData
            }
        } catch {
            print(error)
        }
        return nil
    }

    static func parse(jsonData: Data) {                             //Parsing the JSON data
        do {
            let configuration = try JSONDecoder().decode(Configuration.self, from: jsonData)
            print("developer: ",configuration.developer)
        } catch {
            print("decoded error")
        }
    }
}

Here is main.swift:

import Foundation

let developer = Configuration.readJsonData(forName: "configuration")
print("\(developer)")

KKishore
  • 11
  • 1

0 Answers0