Error Domain = NSCocoaErrorDomain Code = 3840“No value。”UserInfo = {NSDebugDescription = No value。}

时间:2016-04-06 21:02:56

标签: ios json nsdata

我正在学习JSON。我在从URL解析JSON时遇到问题。错误是"错误域= NSCocoaErrorDomain代码= 3840"没有值。" UserInfo = {NSDebugDescription =无值。}"

JSON有效 - 我已经检查过了。这是JSON的结构:

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

这是我的代码:     导入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 个答案:

答案 0 :(得分:0)

您需要实际使用文件中的数据:

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 } ...