如何避免"错误域= NSCocoaErrorDomain Code = 3840"在斯威夫特?

时间:2018-01-31 09:22:04

标签: ios json swift

在尝试解析Swift中的JSON响应时,我一直收到此特定错误:

  

错误域= NSCocoaErrorDomain代码= 3840"没有值。" UserInfo = {NSDebugDescription =无值。}

代码:

    let dict = [
        "phone": phone,
        "firstname": "\(String(describing: firstName))",
        "lastname": "\(String(describing: lastName))"
        ]
        as [String: Any]

    if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {

        var request = URLRequest(url: URL(string: "\(config.baseURL)employee")!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        request.timeoutInterval = 30.0

        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            if error != nil {
                DispatchQueue.main.async {
                    self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
                    return
                }
            }

            guard let data_ = data else {
                return
            }

            do {
                let jsonObj = try JSONSerialization.jsonObject(with: data_, options: .mutableContainers) as? NSDictionary

                guard let parseJSON = jsonObj else {
                    return
                }

                self.navigationItem.rightBarButtonItem = self.rightBarButton


                let meta = parseJSON["meta"] as? [String:Any]
                let status = meta!["status"] as? String


                if status == "200" {
                    isEmployeeModified = true
                    self.dismiss(animated: true, completion: nil)

                } else {
                    let info = meta!["info"] as? String
                    let message = meta!["message"] as? String
                    DispatchQueue.main.async {

                        self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
                    }
                }

            } catch let error as NSError {
                print(error)
            }
        }
        task.resume()

我在项目的其他部分使用了类似的代码,一切都结束了。

2 个答案:

答案 0 :(得分:1)

根据此错误,您服务器的响应无效JSON 您可以使用responseString代替responseJSON,如下所示

 Alamofire.request(URL, method: requestMethod, parameters: params).responseString{ response in
    print(response)
}

答案 1 :(得分:0)

我能够弄清楚出了什么问题,我将在这里为未来的读者解释一下。显然,我正在以错误的方式执行GET请求,因此当我打算执行POST请求时,由于某种原因,它仍然将其视为GET请求,这就是我一直得到响应的原因:错误域= NSCocoaErrorDomain代码= 3840“没有价值。” UserInfo = {NSDebugDescription =无值。}

以下是我重构的代码,它没有任何麻烦:

    let dict = [
        "phone": phone,
        "firstname": firstName,
        "lastname": lastName
        ] as [String : Any]

    guard let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
        return
    }

    guard let url = URL(string: "\(config.baseURL)employee") else {
        return
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData as Data
    request.timeoutInterval = 10

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in

        if let response = response {
            print("JSON Response: \(response)")
        }

        if error != nil {
            DispatchQueue.main.async {
                self.navigationItem.rightBarButtonItem = self.rightBarButton
                self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
                return
            }
        }

        if let data = data {
            do {
                let parseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary

                let meta = parseJSON!["meta"] as? [String:Any]
                let status = meta!["status"] as? String


                if status == "200" {
                    isEmployeeModified = true
                    self.dismiss(animated: true, completion: nil)

                } else {
                    let info = meta!["info"] as? String
                    let message = meta!["message"] as? String
                    DispatchQueue.main.async {
                        self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
                    }
                }
            } catch {
                print(error)
            }
        }
    }.resume()