我试图从这个示例 JSON 中获取填充信息的详细视图中的标签https://api.myjson.com/bins/18qzq5
,我能够填充 tableView,但无法获取行的 indexPath,并且在 detailView 中我收到错误“意外发现 nil 而展开一个可选值”。我在下面列出的代码: * 顺便说一下,我使用的是 swift Decoder
[
{
"name": "New York",
"state": "New York",
"detail": "The largest city in the US"
},
{
"name": "Los Angeles",
"state": "California",
"detail": "Second largest city in the US"
}
]
tableView 的 ViewController
import UIKit
struct City: Codable {
let name: String?
let state: String?
let detail: String?
}
class TableVC: UIViewController {
var citiesList: [City] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let jsonString = "https://api.myjson.com/bins/18qzq5"
guard let url = URL(string: jsonString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
do {
let cities = try JSONDecoder().decode([City].self, from: data)
if cities != nil {
self.citiesList = cities
}else{
print("it's nil")
}
print(self.citiesList)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let jsonErr{
print("error serializing json:", jsonErr)
}
}.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailVC = segue.destination as? DetailTaskVC
let city = sender as AnyObject as? City
detailVC?.city = city
}
}
extension TableVC: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return citiesList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = citiesList[indexPath.row].name
return cell
}
}
extension TableVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toDetail", sender: citiesList[indexPath.row])
}
}
DetailViewController
import UIKit
class DetailTaskVC: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
var city: City!
override func viewDidLoad() {
super.viewDidLoad()
self.nameLabel?.text = city.name //Unexpectedly found nil while unwrapping an Optional value
self.stateLabel?.text = city.state
self.detailLabel?.text = city.detail
}
}
希望你们能帮我解决这个问题,或者网上有一个教程,你们可以指出我,因为我搜索了很多并没有积极的结果。