1
votes

I'm learning JSON. I have problem with parsing JSON from URL. The error is "Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}"

JSON is valid - I've checked. This is structure of JSON:

[{"id":33,"name":"5","sort":2},{"id":34,"name":"6","sort":3},{"id":35,"name":"7","sortOrder":4}]

And this is my code: import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()


    let urlAsString = "http://www.url.address/"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()
    let username = "admin"
    let password = "admin"

    struct Address {

        let name: String?
        let id: String?
        let sortOrder: String?

        init(dict: [String: AnyObject]) {

            name = dict["name"] as? String
            id = dict["id"] as? String
            sortOrder = dict["sort"] as? String
        }
    }
    let path = NSBundle.mainBundle().pathForResource("sections", ofType: "json")
    let jsonData = NSData()

    do {
        if let jsonDic = try NSJSONSerialization.JSONObjectWithData(jsonData,
            options: .MutableContainers) as? [String: AnyObject] {

                let addr = Address(dict: jsonDic)                    
                print("jsonDic")
        }

        } catch let error as NSError {
            print(error)
        }
}
func backButton(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: {})
}

}

1
jsonData is an empty NSData object. What do you expect? - Joking aside you have to get the data from the pathvadian
... and declare model structs at least on the top level of the class rather than in a methodvadian

1 Answers

0
votes

You need to actually use the data from the file:

guard let path = NSBundle.mainBundle().pathForResource("sections", ofType: "json"), let jsonData = NSData(contentsOfFile: path) else { fatalError("Cannot find or load the sections file in the main bundle") } do { if let sections = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as? [String: AnyObject] { // work with sections } ...