json - 为什么除了纬度和经度之外的所有内容的 JSON 都返回为零?
问题描述
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 = “(字符串(描述:weatherList[indexPath.row].latitude))”
但现在在我的通话中唯一返回零的信息是纬度和经度。为什么从我的 JSON 调用成功返回的唯一内容为零?我是不是叫错了什么?感谢您迄今为止的所有帮助。如果我应该发新帖子,请告诉我。我认为这是同一个主题,因为它与我昨天的原始帖子几乎相同。
Stackoverflow 本身不会让我在不添加更多文本的情况下发布,但因为我已经说了我需要说的一切,这只是填充物。
解决方案
为了获得更好/更清洁的代码,也许您想将 API 调用分离到一个函数中(可能func makeRequest()
是什么),以便仅在您的viewDidLoad.
你有
var weatherList: [weatherJSON] = []
这是一个包含您希望表格显示的 weatherJSON 对象的列表,但问题出在您的请求中,您正在重新加载表格中的数据,但您没有将 JSON 响应保存在weatherList
. 您应该首先将 JSON 响应保存在变量中weatherList
或将结果附加到该数组。这样做,您将能够在以下情况下填充您的表格:cell.nameLabel?.text = weatherList[indexPath.row]
此外,您需要添加要显示的天气列表对象的属性。类似weatherList[indexPath.row].name
或对象具有的属性的名称。
此外,我建议使用一些库来发出 HTTP 请求,例如 AlamoFire 和 SwiftyJson,以将您的 JSON 响应映射到您的对象。
使用我提到的库,您的整个 API 调用和表函数可以像这样 func getWeather(){
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)")
}
}
在你的表函数中:
cell.nameLabel.text = self.weatherList[indexPath.row].name
这可以通过 AlamoFireWrapper 类来实现,这样可以发布和获取请求:AlamoFireWrapper.swift
import UIKit
import Alamofire
import SwiftyJSON
class AFWrapper: NSObject {
class func requestGETURL(_ strURL: String, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void) {
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}
推荐阅读
- amazon-web-services - s3上传拆分输出
- c# - .NET Core System.Drawing.Common PrintDocument 在 Linux 上不起作用
- c++ - 安装 BLAS 时遇到问题,以及 CMakeLists 的用途?
- python - 通过SSH从python连接Gitlab部署公钥
- java - 有没有办法使用场景形式测量房间的尺寸?
- javascript - 在 React JS 应用程序中处理通过 HTML 表单提交完成的发布请求
- ios - 触摸手势在 Scrollview(Xcode、Swift)中不起作用
- python - BeautifulSoup 和 CSV:每个字符后的分隔符
- python - 以特殊字符为标记搜索多个子字符串
- jspdf - 有没有办法在一个单元格中为每个单词设置自己的颜色?