Read file in macOS command line project

I have added some JSON files to my macOS command line project, but I cannot find them in the usual way.

if let path = Bundle.main.path(forResource: "Data", ofType: "json")
{
    if let contents = try? String(contentsOfFile: path)
    {
        print (contents)
    }
    else { print("Could not load contents of file") }
}
else { print("Could not find path") }

This code works absolutely fine when used in a view-based application, but always prints "Cannot find the path" in the command line tool.

Does anyone know what I'm doing wrong?

PS: Fully aware that for this I must use instructions for this guard, but the code is not in the function, just cheating in main.swift until I figure it out.

+10
source share
2 answers

There is no command line tool application. Just binary.

JSON ( ?)

+7

, , . :

  1. Xcode, β†’ β†’ ...
  2. MacOS
  3. Framework & Library, Bundle, Next. JSONMocks (, JSONMocks).
  4. . Xcode, , :

    target membership for file in bundle

  5. . +. " ":

    enter image description here

  6. :

let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let bundleURL = URL(fileURLWithPath: "JSONMocks.bundle", relativeTo: currentDirectoryURL)
let bundle = Bundle(url: bundleURL)
let jsonFileURL = bundle!.url(forResource: jsonFileName, withExtension: "json")!
0

Source: https://habr.com/ru/post/1676576/


All Articles