How can I define Content-type in Swift using NSURLSession
This worked for me in developing an iOS application using SWIFT 5 for API calls. The GET method worked fine without these 2 lines. The PUT and the POST methods would send the values to the API server, but once it reached the server it couldn't interpret the JSON data, so my database would insert NULL values for all of the fields. After adding these 2 lines, the data was transferred into the tables correctly. Hopefully, this saves someone else time.
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
If you want to set the Content-Type
of the request, you can create your own URLRequest
, supplying your URL, specify the Content-Type
header using setValue(_:forHTTPHeaderField:)
and then issue the request with the URLRequest
instead of the URL
directly. And just set the httpBody
to be that JSON and specify the httpMethod
of POST
:
let url = URL(string: "https://api/jobmanagement/PlusContactAuthentication")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.httpMethod = "POST"
let dictionary = ["email": username, "userPwd": password]
request.httpBody = try! JSONEncoder().encode(dictionary)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "Unknown error") // handle network error
return
}
// parse response; for example, if JSON, define `Decodable` struct `ResponseObject` and then do:
//
// do {
// let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)
// print(responseObject)
// } catch let parseError {
// print(parseError)
// print(String(data: data, encoding: .utf8)) // often the `data` contains informative description of the nature of the error, so let's look at that, too
// }
}
task.resume()
For Swift 2 rendition, see previous revision of this answer.