如何使用具有 urlsession 的功能更新 TableViewCell? Swift

How to update TableViewCell with function having urlsession? Swift

我有一个函数可以获取位置坐标并获取天气数据。该函数在代码的其他地方使用。

目前我直接在 cellForRowAt 中使用 urlsession 但不想重复代码。有没有办法在 TableViewController 的 cellForRowAt 中调用这个天气函数来更新单元格?

class Data {
    static func weather (_ coord:String, completion: @escaping...([String?]) -> (){

        let url = URL(string: "https://")

        let task = URLSession.shared.dataTask(with: url!) { data, response, error in

        let json = processData(data) //returns [String]?

        completion(json)
        }
        task.resume()


    }

    static func processData(_ data: Data) -> [String]? {

    }
}

在cellForRowAt中,如何修改weather函数在返回单元格之前在这里获取值,但是weather函数的完成功能也应该保留?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ...
    Data.weather() ** ??? **
    cell.label.text = "" // value from weather
    return cell
}

cellForRowAt indexPath 中触发网络调用是个坏主意。只要用户滚动 table 视图,就会调用该方法。这可能会导致大量网络调用。

相反,您应该:

  • 仅在需要时进行网络呼叫。例如,您可以在 viewWillAppear 中完成。每次应用切换到您的 tableView
  • 时都会调用此方法
  • 在模型中存储 网络调用的结果。这可以像 array.
  • 一样简单
  • reloadData重绘table视图
  • cellForRowAt indexPath 中使用来自 array 的数据配置单元格。

让我们看一个例子(它不完整,但应该给你一个想法,该怎么做):

class WeatherTableView: UITableView {
  var weatherData: [String]

  override func viewWillAppear(_ animated: Bool) {
    loadWeatherData()
  }

  private func loadWeatherData() {
    // I just set some data here directly. Replace this with your network call
    weatherData = ["Here comes the sun", "Rainy with chance of meatballs", "It's raining cats and dogs"]
    // Make sure the tableView is redrawn
    tableView.reloadData()
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "weatherDataCell")
    cell.label.text = weatherData[indexPath.row]
    return cell
  }
}