我正在尝试从本地文件加载一些 JSON 数据。
In 这个苹果文档 https://developer.apple.com/library/ios/documentation/ToolsLanguages/Conceptual/Xcode_Overview/AddingDataSets.html它说:
使用资产目录管理应用程序的数据文件。一个文件可以
包含除由生成的设备可执行代码之外的任何类型的数据
Xcode。您可以将它们用于 JSON 文件、脚本或自定义数据类型
所以我添加了一个新的数据集并将 JSON 文件放入其中。现在我可以在 Assets.xcassets 文件夹下看到它(Colours.dataset 文件夹,其中包含 Colours.json 和 Contents.json)
I found this https://stackoverflow.com/questions/24410881/reading-in-a-json-file-using-swiftSO 答案展示了如何读取 JSON 文件,我正在使用此代码来读取该文件:
if let filePath = NSBundle.mainBundle().pathForResource("Assets/Colours", ofType: "json"), data = NSData(contentsOfFile: filePath) {
print (filePath)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print(json)
}
catch {
}
} else {
print("Invalid file path")
}
但是这段代码正在打印“文件路径无效”并且不读取文件。我也尝试过“Colours”和“Colours.json”但无济于事。
谁能告诉我如何正确添加本地 JSON 文件并读取它?
Thanks.
您无法像访问随机文件一样访问数据资产文件NSBundle.pathForResource
。由于它们只能在以下范围内定义Assets.xcassets
,你需要初始化一个NSDataAsset
实例以访问它的内容:
let asset = NSDataAsset(name: "Colors", bundle: NSBundle.mainBundle())
let json = try? NSJSONSerialization.JSONObjectWithData(asset!.data, options: NSJSONReadingOptions.AllowFragments)
print(json)
请注意NSDataAsset
该类从 iOS 9.0 和 macOS 10.11 开始引入。
斯威夫特3版本:
let asset = NSDataAsset(name: "Colors", bundle: Bundle.main)
let json = try? JSONSerialization.jsonObject(with: asset!.data, options: JSONSerialization.ReadingOptions.allowFragments)
print(json)
另外,NSDataAsset 令人惊讶地位于 UIKit/AppKit 中,因此不要忘记在代码中导入相关框架:
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)