我需要从项目子文件夹中读取json
我的代码是:
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
在这种情况下我的错误是什么?
答案 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)
}
}