我有一个关于使用 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(destination: .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 }
关于iOS | Alamofire,如何将原始 JSON 数据发送到正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71558273/