我实现了以下代码
AF.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default).responseData(completionHandler: {response in
print(response)
switch response.result {
case .success:
print(response.result)
let alertVC = self.alertservices.alert(title: "Add Recipe : Basic Level", message: "Your basic level recipe details has been submitted successfully!", cancelTitle: "Cancel", submitTitle: "Ok", alertimage: "recipes"){
self.detailContainerView.isHidden = false
}
self.present(alertVC,animated: true)
break
case .failure :
let alertVC = self.alertservices.alert(title: "Add Recipe : Basic Level", message: "Something went wrong. Please try again!", cancelTitle: "Cancel", submitTitle: "Ok", alertimage: "recipes"){
}
self.present(alertVC,animated: true)
break
}
})
如果使用.responseData
,则会得到此输出success(118 bytes)
,而不是下面提到的内容。但是,当我将值放在邮递员中时得到的实际响应是
{
"response": "success",
"status": 0,
"recipe_id": 10422
}
如果我使用.responseJSON
,则在控制台上显示以下错误。
["recipe_preparation_time": "00:10:00", "recipe_title": "test recipe", "recipe_category": "2", "veg_status": "1", "recipe_food_type[]": [1, 3], "type": "3", "recipe_cooking_time": "00:10:00", "recipe_country": "", "customer_id": "5", "added_by": "5", "difficulty_level": "1"]
success({
error = {
"recipe_food_type" = (
"The recipe food type field is required."
);
};
message = "Validation Error";
status = 406;
})
有人可以帮我解决这个问题吗?
AF.request(url).validate().responseDecodable(of: Response.self) { response in
// and then on response.value you have your response struct
}
JSONDecoder()
进行解码:struct Response: Codable {
let response: String
let status, recipeId: Int
enum CodingKeys: String, CodingKey {
case response, status
case recipeId = "recipe_id"
}
}
为您的请求添加此格式:
AF.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default).validate().responseDecodable(of: Response.self) { response in