Как извлечь конкретные данные из нескольких ответов с помощью Alamofire

#ios #arrays #json #swift #alamofire

#iOS #массивы #json #swift #alamofire

Вопрос:

Я создаю приложение для изучения swift. Мое приложение отправляет запрос в yelpApi. В ответе отображается информация (имена, местоположение, адрес и т. Д.) Для нескольких ресторанов по местоположению. Я могу отобразить название ресторана, адрес, тип для одного ресторана. Как я могу отобразить данные для нескольких ресторанов. Я создал array и append, но я всегда получаю данные для одного ресторана.

Спасибо за все ответы

Моя модель класса

»’

 Class ApiRestaurantDataModel {

    var restaurantName : String?
    var restaurantLocation : String?
    var restaurantType : String?
    var restaurantRating : Int?

    init(restaurantName: String?, restaurantLocation: String?, restaurantType: String?) {
        self.restaurantName = restaurantName
        self.restaurantLocation = restaurantLocation
        self.restaurantType = restaurantType
    }


}
 

»’

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DiscoverTableViewCell



        cell.discoverImage.image = images
        cell.restaurantNameLabel.text = apiDataModel[indexPath.row].restaurantName
        cell.restaurantLocationLabel.text = apiDataModel[indexPath.row].restaurantLocation
        cell.typeLabel.text = apiDataModel[indexPath.row].restaurantType

        return cell
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return apiDataModel.count
    }

// Networking 

 func search(url: String, parameters : [String:String]) {
        let headers: HTTPHeaders = ["Authorization":"Bearer (apiKey)"]
        Alamofire.request(url, method: .get, parameters: parameters, headers: headers ) .responseJSON{
            URLResponse in
            //print(URLResponse)
            if URLResponse.result.isSuccess {
                let yelpDataJSON = JSON(URLResponse.value!)
              print(yelpDataJSON)
                self.updateYelpData(Json: yelpDataJSON)

            }else{
                print("error")
            }

        }
    }



func updateYelpData(Json : JSON){

       if  let nameJSON = Json["businesses"][0]["name"].string {

       let  locationJSON = Json["businesses"][0]["location"]["display_address"][0].stringValue
      let typeJSON = Json["businesses"][0]["categories"][0]["alias"].stringValue

          let data = ApiRestaurantDataModel(restaurantName: nameJSON, restaurantLocation: locationJSON, restaurantType: typeJSON)
        apiDataModel.append(data)


        print(apiDataModel.count)
       let imageUrlJSON = Json["businesses"][0]["image_url"].string
        imageURL = imageUrlJSON!




        loadImage()
         tableView.reloadData()
        }else{
            print("error")
        }
    }
 

Значение ответа Json

 {
  "businesses" : [
    {
      "distance" : 235.19630722374731,
      "rating" : 4.5,
      "phone" : " 525555218815",
      "display_phone" : " 52 55 5521 8815",
      "url" : "https://www.yelp.com/biz/el-cardenal-ciudad-de-méxico-2?adjust_creative=A4ydpSOHv8wBNquTDeh0DQamp;utm_campaign=yelp_api_v3amp;utm_medium=api_v3_business_searchamp;utm_source=A4ydpSOHv8wBNquTDeh0DQ",
      "price" : "$",
      "name" : "El Cardenal",
      "location" : {
        "address2" : "",
        "state" : "DIF",
        "zip_code" : "06000",
        "country" : "MX",
        "city" : "Ciudad de México",
        "address1" : "Calle de la Palma 23",
        "display_address" : [
          "Calle de la Palma 23",
          "06000 Ciudad de México, CDMX",
          "Mexico"
        ],
        "address3" : null
      },
      "is_closed" : false,
      "id" : "Vr7pWwSpDGtr7Dk_wJJzhA",
      "review_count" : 221,
      "transactions" : [

      ],
      "alias" : "el-cardenal-ciudad-de-méxico-2",
      "coordinates" : {
        "longitude" : -99.135253714120793,
        "latitude" : 19.433706059965399
      },
      "categories" : [
        {
          "title" : "Mexican",
          "alias" : "mexican"
        }
      ],
      "image_url" : "https://s3-media3.fl.yelpcdn.com/bphoto/7hNTc7V1q3737rxkTf-drQ/o.jpg"
    },
    {
      "distance" : 116.24557090185914,
      "phone" : " 525555212048",
      "rating" : 4,
      "display_phone" : " 52 55 5521 2048",
      "url" : "https://www.yelp.com/biz/café-de-tacuba-méxico?adjust_creative=A4ydpSOHv8wBNquTDeh0DQamp;utm_campaign=yelp_api_v3amp;utm_medium=api_v3_business_searchamp;utm_source=A4ydpSOHv8wBNquTDeh0DQ",
      "price" : "$",
      "name" : "Café de Tacuba",
      "location" : {
        "address3" : "",
        "address1" : "Calle de Tacuba 28",
        "country" : "MX",
        "address2" : "Col. Centro",
        "city" : "México, D.F.",
        "display_address" : [
          "Calle de Tacuba 28",
          "Col. Centro",
          "06010 México, D.F.",
          "Mexico"
        ],
        "zip_code" : "06010",
        "state" : "DIF"
      },
      "is_closed" : false,
      "id" : "DBQvLnAqV-MXPkA0XMi5aQ",
      "review_count" : 232,
      "transactions" : [

      ],
      "alias" : "café-de-tacuba-méxico",
      "coordinates" : {
        "longitude" : -99.137562322962197,
        "latitude" : 19.4356993121581
      },
      "categories" : [
        {
          "title" : "Mexican",
          "alias" : "mexican"
        }
      ],
      "image_url" : "https://s3-media1.fl.yelpcdn.com/bphoto/_ooR7uHUx2okb7EQd12Ojw/o.jpg"
    }

'''
 

Комментарии:

1. Ясно видно, что вы берете первый элемент (0-й индекс) из массива businesses object и добавляете его в apiDataModel массив. Итак, чего вы ожидаете? Вам нужно зациклить businesses массив и добавить каждый объект в apiDataModel массив, чтобы иметь возможность отображать все элементы.

2. О, я понимаю. Не думал об этом . Спасибо