import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
var weatherList: [weatherJSON] = []
func downloadJSON() {
let jsonUrlString = "https://api.darksky.net/forecast/59c6b6b7efd5c3fc0f617338cfae6c48/40.7127,-74.0059"
guard let url = URL(string: jsonUrlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
do {
let JSON = try JSONDecoder().decode(weatherJSON.self, from: data)
self.weatherList.append(JSON)
print(self.weatherList)
DispatchQueue.main.async {
self.tableview.reloadData()
}
} catch let jsonErr {
print("Error serializing json", jsonErr)
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
downloadJSON()
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weatherList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! countryCell
cell.nameLabel?.text = "\(String(describing: weatherList[indexPath.row].latitude))"
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segue1", sender: nil)
}
}
编辑:我使用字符串插值成功调用了JSON数据 -
cell.nameLabel?.text =“(String(describe:weatherList [indexPath.row] .latitude))”
但现在唯一能在我的电话中回复零的信息是纬度和经度。为什么从我的JSON调用返回的唯一内容成功为零?我错误地打电话了吗?到目前为止,感谢您的帮助。如果我要发一个新帖子,请告诉我。我认为这是在同一主题,因为它与我昨天发布的原始帖子几乎相同。
Stackoverflow本身不会让我发布而不添加更多文本,但因为我已经说过我需要说的一切,这只是填充。
为了获得更好/更清晰的代码,也许你想在一个函数中分离你的API调用(可能是func makeRequest()
或其他东西),以便只在你的viewDidLoad.
中调用该函数
你有
var weatherList: [weatherJSON] = []
这是一个包含您希望表格显示的weatherJSON对象的列表,但问题出在您的请求中,您正在重新加载表格中的数据但是您没有在Qazxswpoi中保存您的JSON响应。您应该首先在变量weatherList
中保存JSON响应,或将结果附加到该数组。这样做,您将能够在以下时间填充您的表:weatherList
此外,您还需要添加要显示的weatherlist对象的属性。像cell.nameLabel?.text = weatherList[indexPath.row]
或对象具有的属性名称。
此外,我建议使用一些库来发出像AlamoFire和SwiftyJson这样的HTTP请求,以将JSON响应映射到您的对象。
使用我提到的库,您的整个API调用和表函数可以像这样的函数getWeather(){
weatherList[indexPath.row].name
在你的表中func:
let url: String = "http://example.com/api/weather/"
AFWrapper.requestGETURL(url, success: {
(JSONResponse) -> Void in
for item in JSONResponse{
let weatherList = [WeatherList(fromJson: item.1)]
for weather in weatherList {
self. weatherList.append(weather)
}
}
self.tableView.reloadData()
})
{
(error) -> Void in
print("Error \(error)")
}
}
这可以通过AlamoFireWrapper类来实现发布和获取请求,如下所示:AlamoFireWrapper.swift
cell.nameLabel.text = self.weatherList[indexPath.row].name