Почему при использовании Alamofire таким способом ничего не найдено? - PullRequest
0 голосов
/ 10 апреля 2019

Я использую Alamofire для звонка на Yummly.com, который должен отправить мне обратно массив с несколькими рецептами.При вызове API все работает нормально.Но когда я пытаюсь добавить эти множественные ответы в значение, с этим сообщением происходит ошибка:

valueNotFound (Swift.Int, Swift.DecodingError.Context (codingPath: [CodingKeys (stringValue: ")соответствует ", intValue: nil), _JSONKey (stringValue:" Index 5 ", intValue: 5), CodingKeys (stringValue:" totalTimeInSeconds ", intValue: nil)], debugDescription:" Ожидаемое значение Int, но вместо него найден ноль. ", лежащий в основе ошибки: 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
        },

1 Ответ

0 голосов
/ 10 апреля 2019

Проблема возникла из-за «timer: result.totalTimeInSeconds», который возвращается ноль в один момент, когда вызов API возвращается с результатом «ValueNotFound».

timer: result.totalTimeInSeconds ?? 0
...