在this Apple doc它说:
Manage the data files for your app using the asset catalog. A file can
contain any sort of data except device executable code generated by
Xcode. You can use them for JsON files,scripts,or custom data types
所以我添加了一个新数据集并将JsON文件放入其中.现在我可以在Assets.xcassets文件夹下看到它(Colours.dataset文件夹里面有colours.Json和Contents.Json)
我找到了this SO答案,显示了如何读取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.Json”,但无济于事.
谁能告诉我如何正确添加本地JsON文件并阅读它?
谢谢.
解决方法 您无法使用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.
Swift3版本:
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总结
以上是内存溢出为你收集整理的ios – 添加JSON作为资产并阅读它全部内容,希望文章能够帮你解决ios – 添加JSON作为资产并阅读它所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)