在macOS命令行工具项目中读取文件

17

我已将一些 JSON 文件添加到我的 macOS 命令行工具项目中,但通常的方式似乎无法找到它们。

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") }

这段代码在基于视图的应用程序中使用时完全正常,但在命令行工具中总是打印“找不到路径”。

有人知道我做错了什么吗?

P.S: 完全意识到我应该使用guard语句,但这段代码不在函数中,我只是在main.swift中瞎搞,直到我弄清楚为止。

2个回答

24

您可以创建一个单独的bundle,将文件放在其中,然后加载它们而不必担心它们各自的URL。

让我们开始:

  1. 在Xcode中,点击 File --> New --> Target...
  2. 点击顶部的macOS选项卡
  3. 向下滚动到Framework & Library,选择Bundle,然后点击下一步。给新包命名(假设为JSONMocks)。
  4. 将文件添加到此bundle中。将文件添加到Xcode中,然后确保在其target membership部分中选中了该bundle:

    target membership for file in bundle

  5. 将bundle添加到您的目标中。在目标的Build Phases中,打开Copy Files阶段并点击+按钮。选择bundle并点击Add

    enter image description here

  6. 通过编程方式访问bundle中的内容:

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")!

13

对于命令行工具而言,没有应用程序捆绑包,只有二进制文件。

您需要将JSON文件放在已知位置(当前目录?),并自己构建路径。


1
谢谢!有没有什么好的方法可以获取相对于当前.xcodeproj文件的文件路径?(试图将文件包含在git存储库中) - XmasRights
2
https://dev59.com/HFwZ5IYBdhLWcg3wafx6 - Lou Franco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接