Ответ 1
Если вы хотите установить Content-Type
запроса, вы можете создать свой собственный URLRequest
, указав свой URL, указать заголовок Content-Type
используя setValue(_:forHTTPHeaderField:)
а затем выполнить запрос с URLRequest
вместо URL
непосредственно. И просто установите httpBody
как JSON и укажите httpMethod
для POST
:
let url = URL(string: "http:/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 look at that, too
// }
}
task.resume()
Для воспроизведения Swift 2 см. Предыдущую редакцию этого ответа.