SwiftyJSON to read local file
Asked Answered
B

1

1

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

        }
Barcus answered 15/11, 2015 at 6:58 Comment(0)
R
0

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.

Rockaway answered 15/11, 2015 at 13:12 Comment(7)
Nope. Doesn't works. Its still blank. I saw this syntax in their official page and tried earlier as well, it doesn't work.Barcus
Ok. You should keep using this explicit "data:" syntax when using an NSData source anyway, it will avoid creating other errors later. // If your file does not accidentally contain an empty array then I don't see what can be happening here, sorry. Hope someone else finds out.Rockaway
The JSON has a valid data. Actually if i copy the same json file in a node server and access it using Alamofire + SwiftyJSON it works perfectly. Somehow it doesn't works when i try to access the local file.Barcus
Ah, thanks for this info. But that's weird indeed. With your code and adding "data:" it works for me in a sample project.Rockaway
Really. Would you mind sharing the project with me please?Barcus
Not at all, I just made a zip, you can download it here: dropbox.com/s/wbz9519c1fh92fs/TestJSONFile.zip?dl=0 (this is an OSX project but I just tested in an iOS project and it alsoworks)Rockaway
Hi Eric, Thanks for your help. So figured out the issue. Issue is with one of the sample data i have. Now what is interesting is if i validate the JSON data it validates properly but somehow the SwiftyJSON won't able to read it. Also a online version of the same file works. Anyways now i know where is the issue and to look for. Thanks for helping. Cheers!\ [FYI. Renaming the file worked - for anyone having same issue]Barcus

© 2022 - 2024 — McMap. All rights reserved.