我正在使用Alamofire在Yummly.com上打电话,这应该将我发送回包含多个配方的数组。进行API调用时,一切工作正常。但是,当我尝试将多个响应添加到一个值中时,出现以下错误信息:
valueNotFound(Swift.Int,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ matches”,intValue:nil),_JSONKey(stringValue:“ Index 5”,intValue:5),CodingKeys(stringValue:“ totalTimeInSeconds”,intValue:nil)],debugDescription:“预期的Int值,但发现为null。”,底层错误:nil))
struct RecipeSearchResult: Decodable {
let name: String?
let ingredients: String?
let image: URL?
let rating: Int?
let timer: Int?
}
struct SearchRecipesRoot: Decodable {
let matches: [Matches]
}
struct Matches: Decodable {
let recipeName: String
let smallImageUrls: [URL]
let ingredients: [String]
let id: String
let totalTimeInSeconds: Int
let rating: Int
}
func searchRecipes(from userIngredients: String) {
let urlSearchParameter = "&q=\(userIngredients)&requirePictures=true"
let searchURL = URL(
string: "https://api.yummly.com/v1/api/recipes?" + urlAPIParameter + urlSearchParameter)!
Alamofire.request(searchURL, method: .get).responseJSON {
(response) in
guard response.result.isSuccess else {
print("☠️ \(String(describing: response.result.error)) ☠️")
return
}
do {
let responseJSON = try JSONDecoder().decode(SearchRecipesRoot.self, from: response.data!)
for result in responseJSON.matches {
let recipiesSearchResult = RecipeSearchResult(
name: result.recipeName,
ingredients: result.ingredients.joined(separator: "\n"),
image: result.smallImageUrls[0],
rating: result.rating,
timer: result.totalTimeInSeconds
)
print(recipiesSearchResult)
}
}
catch {
print(error)
}
}
}
这是JSON响应,其重复次数与找到的食谱相同:
{
"criteria": {
"q": "pasta tomatoes cheese salmon",
"requirePictures": true,
"allowedIngredient": null,
"excludedIngredient": null
},
"matches": [
{
"imageUrlsBySize": {
"90": "https://lh3.googleusercontent.com/7lLNUgFrzS0rHdWGYKhv4qnVg2mPkafkZzSqUWYrFCOJpV4xq_KwU5HuB8KGHdn40G-s-RQQISyaCyPdJWCxpA=s90-c"
},
"sourceDisplayName": "The Washington Post",
"ingredients": [
"dried pasta",
"olive oil",
"vidalia onion",
"garlic",
"tomatoes",
"cream cheese",
"smoked salmon",
"freshly ground black pepper",
"basil leaves",
"parmesan cheese"
],
"id": "Tomato-and-Smoked-Salmon-Pasta-2161877",
"smallImageUrls": [
"https://lh3.googleusercontent.com/R1P8lKMQZz__M77Pav5ptnX2gdzxqY1wj6xzIaxHNuFFT6xe3QQ5E-nxgEROOJ2S0GUjpNruHrsNk-c0G9fO=s90"
],
"recipeName": "Tomato and Smoked Salmon Pasta",
"totalTimeInSeconds": 2100,
"attributes": {
"course": [
"Main Dishes"
]
},
"flavors": {
"piquant": 0,
"meaty": 0.16666666666666666,
"bitter": 0.3333333333333333,
"sweet": 0.16666666666666666,
"sour": 0.3333333333333333,
"salty": 0.8333333333333334
},
"rating": 3
},
答案 0 :(得分:0)
问题来自“ timer:result.totalTimeInSeconds”,它在某一时刻返回nil,这使API调用随“ ValueNotFound”结果一起返回。
timer: result.totalTimeInSeconds ?? 0