iOS|Alamofire,如何将原始JSON数据发送到主体



我有一个关于使用Alamofire向端点发送原始JSON的问题。

使用下方的代码

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)
}
}
}

至少我得到了一个失败,即端点想要更多的值(它确实这样做了(

但是,使用编码器URLEncodedFormParameterEncoder(目的地:httpBody(以外的任何其他方法(例如JSONEncoder.default(,请求甚至不会返回响应(成功或失败(。

问题是,我有一个接收多个值(int、string、对象数组(的字典,当我将字典(类型为string:Any(传递给参数时,我会得到一个错误,即作为类型的Protocol"Any"不能符合"Encodable"。

任何答案都将不胜感激

也许你想要这样的东西:

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 }

最新更新