NSCocoaErrorDomain Code = 3840 "Нет значения." - PullRequest
0 голосов
/ 07 мая 2018

Я пытаюсь отправить некоторые данные на сервер и получить ответ .. как это:

     @IBAction func submitbtn(_ sender: Any) {


    let decoded4  = userDefaults.object(forKey: "nationalities") as! Data
    let decodedNationalities = NSKeyedUnarchiver.unarchiveObject(with: decoded4) as! [Nationality]
    for nationality in decodedNationalities {
        if nationality.name == idnationality{
            idnationality = String(nationality.id)
        }

    }
    if conttype == "Single visit"{
        conttype = "single_visit"
    }else {
        conttype = "multi_visit"
    }
    print(days)
    if days.hasPrefix(","){
        days.remove(at: days.startIndex)
    }
    if days.hasSuffix(","){
        days.remove(at: days.endIndex)
    }
    let todosEndpoint: String = "my link"
    guard let todosURL = URL(string: todosEndpoint) else {
        print("Error: cannot create URL")
        return
    }
    var todosUrlRequest = URLRequest(url: todosURL)
    todosUrlRequest.httpMethod = "POST"
    todosUrlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let newTodo: [String: Any] = ["email": UserDefaults.standard.string(forKey: "CustomerEmail")!, "password": UserDefaults.standard.string(forKey: "CustomerPassword")!, "id_address": addid, "quantity_staff": quantitiy, "num_of_visits_per_week": numvisits, "id_service": idservice, "id_region": idregion, "id_city": idcity, "id_nationality": idnationality, "start_date": date, "contract_period": mon, "contract_type": conttype, "shift_type": shif, "weekdays": days]
    print(newTodo)
    let jsonTodo: Data
    do {
        jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
        todosUrlRequest.httpBody = jsonTodo
    } catch {
        print("Error: cannot create JSON from todo")
        return
    }

    let session = URLSession.shared

    let task = session.dataTask(with: todosUrlRequest) {
        (data, response, error) in
        guard error == nil else {
            print("error calling POST on /public/api/register_customer")
            print(error!)
            return
        }
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }

        // parse the result as JSON, since that's what the API provides
        do {
            guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,options: []) as? [String: Any] else {
                 print("Could not get JSON from responseData as dictionary")
            return
            }
            print("The todo is: " + receivedTodo.description)

            guard let status = receivedTodo["success"] as? Int else {
                print("Could not get status from JSON")
                return
            }

            if status == 0{
                DispatchQueue.main.async {
                     self.performSegue(withIdentifier: "segueerr", sender: self)
                }

                print("The status is: 0")
                guard let messages = receivedTodo["message"] as? String else {
                    print("Could not get messages from JSON")
                    return
                }
                    print(messages)


            }
            else {
                DispatchQueue.main.async {
                    self.performSegue(withIdentifier: "successsegue", sender: self)
                }
                print("Success!")
            }
        } catch  {
            print(error)
            return
        }
    }
    task.resume()


}

но я получаю эту ошибку:

Ошибка домена = NSCocoaErrorDomain Code = 3840 «Нет значения». UserInfo = {NSDebugDescription = Нет значения.}

когда все отправлено правильно, как я хочу, как:

 ["contract_period": 0, "email": "lamatat@gmail.com", "id_service": 1, "id_region": 1, "id_city": 3, "id_address": 22, "weekdays": "sun", "contract_type": "single_visit", "num_of_visits_per_week": "1", "id_nationality": "4", "password": "4169faf51ce3c5fb8850451b441a363906f16d69", "shift_type": "day", "quantity_staff": "1", "start_date": "2018-05-06"]

также это работало просто отлично, внезапно это стало таким и отображало эту ошибку!

и я попробовал те же значения от почтальона, и я получил правильный резонанс !!

почему я получаю эту ошибку? что я делаю не так?

скриншоты почтальона:

enter image description here

результат:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...