I am trying to send post request through URLSession
I am constructing my payload using this
let params: [String : Any] = [
"name": username,
"password": password,
"email": email,
"c_password": confirmPassword
]
also with this
var urlParser = URLComponents()
urlParser.queryItems = [
URLQueryItem(name: "name", value: username),
URLQueryItem(name: "password", value: password),
URLQueryItem(name: "email", value: email),
URLQueryItem(name: "c_password", value: confirmPassword)
]
and this setting it to httpBody like this
request.httpBody = parameters.data(using: .utf8)
and calling my function but it throws me the error
The request was well formed but was unable to be followed due to semantic errors
But when I try to send request in this way
let parameters = "name=test&password=Pass@123&c_password=Pass@123&[email protected]"
it works
but when I try to make it dynamic
let parameters = "name=\(username)&password=\(password)&c_password=\(confirmPassword)&email=\(email)"
it gives me error. I am not sure what I am doing wrong
Complete code
if let url = URL(string: Constants.REGISTRATION_URL){
var request = URLRequest(url: url)
request.httpMethod = "POST"
let params: [String : Any] = [
"name": username,
"password": password,
"email": email,
"c_password": confirmPassword
]
var urlParser = URLComponents()
urlParser.queryItems = [
URLQueryItem(name: "name", value: username),
URLQueryItem(name: "password", value: password),
URLQueryItem(name: "email", value: email),
URLQueryItem(name: "c_password", value: confirmPassword)
]
// let httpBodyString = urlParser.percentEncodedQuery
// let parameters = "name=test&password=Pass@123&c_password=Pass@123&[email protected]"
let parameters = "name=\(username)&password=\(password)&c_password=\(confirmPassword)&email=\(email)"
request.addValue("Application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.httpBody = parameters.data(using: .utf8)
APIManager.sharedInstance.postCall(request: request, onSuccess: { json in
DispatchQueue.main.async {
}
}, onFailure: { error in
do{
let errorModel = try JSONDecoder().decode(ErrorModel.self, from: Data(error.utf8))
DispatchQueue.main.async {
self.showAlertMessage(alertMessage: errorModel.errors[0].detail)
}
}catch{
DispatchQueue.main.async {
self.showAlertMessage(alertMessage: error.localizedDescription)
}
}
})
}
The problem is that you're attempting to send a GET query string to a POST request.
GET requests expect a character escaped string (like what you have).
POST requests expect (mostly )a dictionary object (like your param dictionary)
See this answer for how to set a POST request properly