我有一個關于使用 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' as a型別不能符合“可編碼”。
任何答案將不勝感激
uj5u.com熱心網友回復:
也許你想要這樣的東西:
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 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446746.html
