[英]Tableview with JSON Data in Swift 4.2
I'm new to Swift and I am at my wit's end, so please be kind to me. 我是Swift的新手,现在机灵已死,所以请对我好一点。
I am building an app which downloads data from an url by posting a specific ID and getting back an JSON array. 我正在构建一个通过发布特定ID并返回JSON数组从url下载数据的应用程序。 The JSON looks like this:
JSON如下所示:
[{"group":"500","from":"2019-01-01","to":"2019-01-05"},{...}]
It has the group number as "group" and a start Date "from" and an end date "to". 它的组号为“ group”,开始日期为“ from”,结束日期为“ to”。
I want to let the different groups shown in a Tableview with the From and To -Dates as well. 我想让Tableview中显示的不同组也包含From和To -Date。 I managed to download the data correctly but I failed by showing them in a tableview.
我设法正确下载了数据,但通过在表格视图中显示它们而失败。
My code is down below. 我的代码在下面。 Maybe someone of you can find out what I've done wrong.
也许你们当中有人可以找出我做错了什么。
When I run the project I get an empty table. 当我运行项目时,我得到一个空表。
import UIKit
typealias Fahrten = [FahrtenElement]
struct FahrtenElement: Codable {
let group: String?
let from: String?
let to: String?
enum CodingKeys: String, CodingKey {
case group = "group"
case from = "from"
case to = "to"
}
}
class BookingsController: UITableViewController {
var tableview: UITableView!
var groups = [Fahrten]()
// MARK: - Table view data source
override func viewDidLoad() {
super.viewDidLoad()
downloadData()
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "Groups"
label.backgroundColor = .yellow
return label
}
// Section
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.groups.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//lblname to set the title from response
cell.textLabel?.text = "Group \(String(describing: groups[indexPath.row].group))"
cell.detailTextLabel?.text = "From \(String(describing: groups[indexPath.row].from)) to \(String(describing: groups[indexPath.row].to))"
return cell
}
func downloadData() {
let id = "..."
let url = URL(string: "...")!
// request url
var request = URLRequest(url: url)
// method to pass data POST - cause it is secured
request.httpMethod = "POST"
// body gonna be appended to url
let body = "id=(\(id))"
// append body to our request that gonna be sent
request.httpBody = body.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, response, err) in
guard let data = data else { return }
do {
let groups = try JSONDecoder().decode(Fahrten.self, from: data)
print(groups)
self.tableview.reloadData() // I get an crash here: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value }
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
From what I can see it looks like you are emptying the array and not reloading the data. 从我可以看到的情况来看,您似乎正在清空数组而不重新加载数据。
You should assign the resulting groups property to self.groups
and then reload the data. 您应该将结果的groups属性分配给
self.groups
,然后重新加载数据。
DispatchQueue.main.async {
self.groups = groups // change here
self.tableview.reloadData()
}
Try this code. 试试这个代码。
Your model. 您的模型。
typealias Fahrten = [FahrtenElement]
struct FahrtenElement: Codable {
let group: String
let from: String
let to: String
enum CodingKeys: String, CodingKey {
case group = "group"
case from = "from"
case to = "to"
}
}
Use it, I am using it with local json with same structure. 使用它,我将其与具有相同结构的本地json一起使用。
func getFehData(){
let url = Bundle.main.url(forResource: "fah", withExtension: "json")!
do {
let jsonData = try Data(contentsOf: url)
let fahrten = try? JSONDecoder().decode(Fahrten.self, from: jsonData)
print(fahrten)
}
catch {
print(error)
}
}
Output : (Dummy data) 输出:(虚拟数据)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.