【问题标题】:Why do I get the error 'Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}'?为什么我会收到错误“Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=无值。}'?
【发布时间】:2017-02-10 17:37:14
【问题描述】:

我是 Swift 和 iOS 开发的新手,但我正在尝试下载和解析存储在 MySQL 数据库中的数据。

我不断收到错误:

Domain=NSCocoaErrorDomain 代码=3840 "没有价值。" UserInfo={NSDebugDescription=无值。}

我在下面发布了我的代码,但我认为问题不在于 parseJSON 函数,而是在数据的实际下载中,因为当我打印“数据”时它返回“”。

这是我的代码:

//properties

weak var delegate: HomeModelProtocal!

var data : NSMutableData = NSMutableData()

let urlPath: String = "http://localhost/service.php" //this will be changed to the path where service.php lives

// Function to download the incoming JSON data
func downloadItems(){
    let url: URL = URL(string: urlPath)!
    var session: URLSession!
    let configuration = URLSessionConfiguration.default


    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    let task = session.dataTask(with: url)

    task.resume()
}

func urlSession(_ session: URLSession, task: URLSessionDataTask, didCompleteWithError error: Error?) {
    self.data.append(data as Data)
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil{
        print("Failed to download data")
    }else{
        print("Data downloaded")
        print(data)
        self.parseJSON()
    }
}

func parseJSON(){

    var jsonResult: NSMutableArray = NSMutableArray()

    do{
        jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options: []) as! NSMutableArray
    } catch let error as NSError {
        print("**** sake its happened again \(error)")
    }

    var jsonElement: NSDictionary = NSDictionary()
    let locations: NSMutableArray = NSMutableArray()

    for i in 0 ..< jsonResult.count{
        jsonElement = jsonResult[i] as! NSDictionary

        let location = LocationModel()

        //the following insures none of the JsonElement values are nil through optional binding
        if let exerciseName = jsonElement["stationName"] as? String,
            let bodyPart = jsonElement["buildYear"] as? String
        {
            print(exerciseName, bodyPart)
            location.exerciseName = exerciseName
            location.bodyPart = bodyPart

        }

        locations.add(location)

    }

    DispatchQueue.main.async(execute: { () -> Void in

        self.delegate.itemsDownloaded(items:locations)

    })
}

【问题讨论】:

  • 也许响应是空的?你的print(data) 显示了什么?
  • 尝试在邮递员或其他地方执行此操作,并检查是否真的有东西
  • 我已经尝试打印数据并返回", "Body_Part": "武器" },'

标签: ios mysql json swift xcode


【解决方案1】:

你的代码中特别糟糕的地方:

//This method is not being called...
func urlSession(_ session: URLSession, task: URLSessionDataTask, didCompleteWithError error: Error?) {
    self.data.append(data as Data) //<-This line adding self.data to self.data
}

没有将URLSessionDataTask 作为第二个参数的urlSession(_:task:didCompleteWithError:) 方法。所以,这个方法永远不会被调用。

并且在方法内部,self.data 被附加到self.data,所以即使调用了方法,self.data 仍然是空的...

您需要改为实现此方法:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    self.data.append(data)
}

但如果您只想累积接收到的数据,则无需使用委托。

您在 parseJSON() 方法中使用强制转换:

    jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options: []) as! NSMutableArray

不指定.mutableContainers 选项。这也会使您的应用崩溃。

而且你的代码使用了太多的NSSomethings


所有这些东西都修好了,你可以得到这样的东西:

//properties

weak var delegate: HomeModelProtocal!

let urlPath: String =  "http://localhost/service.php" //this will be changed to the path where service.php lives

// Function to download the incoming JSON data
func downloadItems() {
    let url: URL = URL(string: urlPath)!
    let session = URLSession.shared

    let task = session.dataTask(with: url) {data, response, error in
        if let error = error {
            print("Failed to download data: \(error)")
        } else if let data = data {
            print("Data downloaded")
            print(data as NSData)
            //print(String(data: data, encoding: .utf8))
            self.parseJSON(data: data)
        } else {
            print("Something is wrong...")
        }
    }

    task.resume()
}

func parseJSON(data: Data){

    do {
        if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [[String: AnyObject]] {

            var locations: [LocationModel] = []

            for jsonElement in jsonResult {
                let location = LocationModel()

                //the following insures none of the JsonElement values are nil through optional binding
                if let exerciseName = jsonElement["stationName"] as? String,
                    let bodyPart = jsonElement["buildYear"] as? String
                {
                    print(exerciseName, bodyPart)
                    location.exerciseName = exerciseName
                    location.bodyPart = bodyPart

                }

                locations.append(location)

                DispatchQueue.main.async {
                    self.delegate.itemsDownloaded(items: locations)
                }
            }
        } else {
            print("bad JSON")
        }
    } catch let error as NSError {
        print("**** sake its happened again \(error)")
    }
}

【讨论】:

  • 非常感谢您帮助解决我的问题,这已经完美解决了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 2015-09-21
相关资源
最近更新 更多