SwiftyJSON to read local file

非 Y 不嫁゛ 提交于 2019-12-24 14:10:05

问题


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")
            }

        }

回答1:


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.



来源:https://stackoverflow.com/questions/33717251/swiftyjson-to-read-local-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!