简体   繁体   中英

How to use the following data to populate the tableVIew cells?

I am a beginner to iOS development and I am working on a weather app. I am trying to find any solution to the following problem for 3 days now but no clues. So please help me on this.

The problem is How do I use the data fetched from the code below to populate the tableViewCells ?

//TODO: get 3 day forecast
func getWeather() {
    let params: [String:String] = ["q": place!, "appid": APP_ID]
    Alamofire.request(WEATHER_URL ,method: .get, parameters: params).responseJSON { (response) in
        let result = JSON(response.result.value!)
        print(result)
    }
}

func updateTable( json: JSON) {
    print(json["list"].count)
    for i in 0...json.count - 1 {
        self.weatherObject.date = json["list"][i]["dt_txt"].stringValue
        self.weatherObject.temp = json["list"][i]["main"]["temp"].intValue
        self.weatherObject.weather = json["list"][i]["weather"][0]["main"].stringValue
        print(weatherObject.date)
        forecastDate.append(weatherObject.date)
        forecastTemp.append(weatherObject.temp)
        forecastWeather.append(weatherObject.weather)
        print(forecastDate[i])
        print(forecastTemp[i])
        print(forecastWeather[i])
    }
}

weatherObject is an object of weather class that I have created to structure the weather data.

This is really very confusing since whenever I try to pass the arrays that are: forecastWeather, forecastDate, forecastTemp into tableView delegate and datasource methods , there are actually no values in there. Is there any way to sort out this coding problem?

Just save the result into array of structs or classes in your UIViewController. Then implement the following methods:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return yourArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "providerCell", for: indexPath) as! YourTableViewCell
    // set your data to cell

    return cell
}

In your ViewController, when the data download is completed call tableView.reloadData() .

I recommend you to find some tutorial for example https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM