无法从项目子文件夹中读取文件

时间:2018-06-11 12:53:34

标签: ios swift swift4

我需要从项目子文件夹中读取json

我的项目文件夹结构如下所示: enter image description here

我的代码是:

if let url = Bundle.main.url(forResource: "default", withExtension: "json", subdirectory: "Localization"){
            do {
                let data = try Data(contentsOf: url)
                let decoder = JSONDecoder()
                let jsonData = try decoder.decode(Class.self, from: data)

            } catch {
                print("error:\(error)")
            }
        }

我在stackoverflow和其他页面上看到了另一个解决方案,但所有这些解决方案看起来都像我的,但在我的情况下,url总是nil 在这种情况下我的错误是什么?

1 个答案:

答案 0 :(得分:0)

确保您的应用目标default.json中的Copy Bundle Resources中存在Build Phases个文件。

然后你可以使用它来访问它,不需要subdir

if let path = Bundle.main.path(forResource: "default", ofType: "json") {
    do {
        let data = try Data(contentsOf: URL(fileURLWithPath: path))
    } catch {
        print(error.localizedDescription)
    }
}