SwiftyJSON 读取本地文件 [英] SwiftyJSON to read local file

查看:41
本文介绍了SwiftyJSON 读取本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的应用程序使用 JSON API 响应从服务器读取一些数据.由于 API 尚未准备好,我想使用存储在我的应用程序本身中的示例 JSON 文件.由于我的所有代码都使用 SwiftyJSON,因此我想在本地文件中坚持使用它.我在 ViewDidLoad 方法中执行以下操作,不知何故这个最终结果是一个空白数组.您知道我应该在此代码中更改哪些内容才能使其正常工作吗?

So my app is using a JSON API response to read some data from server. Since the API is not yet ready i want to use a sample JSON file which is stored in my app itself. Since all my code uses SwiftyJSON i want to stick to it for the local file. I am doing the following in my ViewDidLoad method and somehow this end result is a blank array. Do you know what should i change in this code to make it work?

//Direct JSON
        if let path = NSBundle.mainBundle().pathForResource("XXYYXZZfile", ofType: "json")
        {
            do{
                let pathAsData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
                let json = JSON(pathAsData)
                print(json)

            } catch{
                print("Some error")
            }

        }

推荐答案

当将 SwiftyJSON 与 NSData 一起使用时,您必须为 JSON 初始值设定项指定data:"参数:

When using SwiftyJSON with NSData you have to specify the "data:" parameter for the JSON initializer:

let json = JSON(data: pathAsData)

否则它会尝试使用 其他可用的初始化程序 并且会因错误而失败,甚至像您的情况一样,会因错误解释的输入和错误的输出而静默失败.

otherwise it tries to use other available initializers and will fail with an error or even, like in your case, will fail silently with a misinterpreted input and wrong output.

这篇关于SwiftyJSON 读取本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆