【发布时间】:2019-03-11 11:34:56
【问题描述】:
我是 Swift 的新手,我已经无能为力了,所以请善待我。
我正在构建一个应用程序,该应用程序通过发布特定 ID 并取回 JSON 数组来从 url 下载数据。 JSON 看起来像这样:
[{"group":"500","from":"2019-01-01","to":"2019-01-05"},{...}]
它的组号为“group”,开始日期为“from”,结束日期为“to”。
我想让 Tableview 中显示的不同组也带有 From 和 To-日期。我设法正确下载了数据,但在表格视图中显示它们失败了。
我的代码在下面。也许你们中的某个人可以找出我做错了什么。
当我运行项目时,我得到一个空表。
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()
}
【问题讨论】:
-
添加
tableview.dataSource=true也取消注释这一行:self.tableview.reloadData()在self.groups = [Fahrten]()之后 -
你为什么评论这个?
// self.tableview.reloadData() -
我在“self.tableview.reloadData()”处发生崩溃。“线程 1:致命错误:在展开可选值时意外发现 nil”
-
你的tableView是nil?也许?你只在 viewDidLoad 中调用 downloadData 吗?你如何初始化视图控制器?
-
尝试在这一行添加断点并单步执行代码。检查检查器中的值以检查 nil