httpBody не передает тело JSON с URLRequest - PullRequest
0 голосов
/ 08 мая 2019

Я пытаюсь POST позвонить с httpBody, содержащей JSON.Когда я запускаю код, я получаю Request JSON object for insert cannot be null. Когда я запускаю тот же URL и тело JSON в PostMan, это работает.Когда я удаляю тело JSON, я получаю ту же ошибку.

let headers = [
    "authorization": "Basic " + base64EncodedCredential!,
    "cache-control": "no-cache"
]

let jsonBody = ["short_description": "this is a test from Xcode",
                "caller_id": "USERNAME",
                "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."]

let url = URL(string: "https://some url")
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 0)

request.httpMethod          = "POST"
request.allHTTPHeaderFields = headers


do {
    request.httpBody = try JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted)

} catch let error {
    print(error.localizedDescription)
}

// Make request
let session = URLSession.shared

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

    if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {

        let decoder = JSONDecoder()

        do {
            let serviceRequest = try decoder.decode(Incident.self, from: data!)


        } catch {
            print("Error: \(error)")

        }

    }  else {


    }

})

task.resume()
...