尝试使用JSON数据填充表格视图。获取tableview = UITableView?无

时间:2018-10-11 14:53:31

标签: ios swift uitableview

我得到

  

线程1:致命错误:展开一个可选值时意外发现nil

DispatchQueue.main.async{ self.tableView.reloadData() }

我的代码

import UIKit

class BrowseRequestsViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {

    final let url = URL(string: "")

    private var browseRequestDataModel = [Datum]()

    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadJson()
    }

    func downloadJson() {
        guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
            guard let data = data, error == nil, urlResponse != nil else {
                print("something is wrong")
                return
            }
            print("downloaded")
            do {
                let decoder = JSONDecoder()
                let downloadedBrowseRequestData = try decoder.decode(BrowseRequestsDataModel.self, from: data)
                self.browseRequestDataModel = downloadedBrowseRequestData.data
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            } catch {
                print("something wrong after downloaded")
            }
        }.resume()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return browseRequestDataModel.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrowseRequestsTableViewCell" ) as? BrowseRequestsTableViewCell else { return UITableViewCell() }

        cell.shipperName.text = browseRequestDataModel[indexPath.row].user.name
        cell.pickupLocation.text = browseRequestDataModel[indexPath.row].pickupLocation.pickupLocationCity + " , " + browseRequestDataModel[indexPath.row].pickupLocation.pickupLocationCountry
        cell.dropoffLocation.text = browseRequestDataModel[indexPath.row].dropoffLocation.dropoffLocationCity + " , " + browseRequestDataModel[indexPath.row].dropoffLocation.dropoffLocationCountry
        cell.item.text = browseRequestDataModel[indexPath.row].item.name
        cell.pickupDate.text = browseRequestDataModel[indexPath.row].pickupDate
        cell.dropoffDate.text = browseRequestDataModel[indexPath.row].dropoffDate

        return cell
    }
}

0 个答案:

没有答案