I have a question about sending a raw JSON to an endpoint using Alamofire.
Using the code below
let request = AF.request("URL OF ENDPOINT", method: .post, parameters: ["FirstName" : "kwstas"], encoder: URLEncodedFormParameterEncoder(destination: .httpBody), headers: headers).responseJSON{ (response) in
//Check the result from Alamofire's response and check if it's a success or a failure
switch response.result {
case .success(let value):
//Everything is fine, return the value in onNext
observer.onNext(value)
observer.onCompleted()
case .failure(let error):
//Something went wrong, switch on the status code and return the error
switch response.response?.statusCode {
case 403:
observer.onError(ApiError.forbidden)
case 404:
observer.onError(ApiError.notFound)
case 409:
observer.onError(ApiError.conflict)
case 500:
observer.onError(ApiError.internalServerError)
default:
observer.onError(error)
}
}
}
At least i get a failure that the endpoint wants more values ( which it does)
But using anything else rather than encoder URLEncodedFormParameterEncoder(destination: .httpBody) (for example JSONEncoder.default) the request doesnt even return a response ( success or failure ).
The thing is that i have a dictionary that receives multiple values ( int, string , array of objects) and when i pass my dictionary (which is of type String : Any) to the parameters i get an error that Protocol 'Any' as a type cannot conform to 'Encodable'.
Any answers will be much appreciated
CodePudding user response:
Maybe you want something like this :
var memberJson : String = ""
do{
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(yourJson)
memberJson = String(data: jsonData, encoding: String.Encoding.utf8)!
}catch{}
var request = URLRequest(url: URL(string: "url here")
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = (memberJson).data(using: .unicode)
AF.request(request).responseJSON{response in }