You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UITableView中展示JSON API数据?代码实现遇阻求助

无法在UITableView中展示JSON数据的排查与解决

问题描述

能成功获取JSON数据,但无法将其显示在UITableView中,不清楚原因。以下是相关代码实现:

模型代码

class PastTripsVC: UIViewController {
    var past = [PastRide]()
    @IBOutlet weak var mTable: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let nibCell = UINib(nibName: "PastTableView", bundle: nil)
        mTable.register(nibCell, forCellReuseIdentifier: "cell")
        apiCalling()
    }

    func apiCalling(){
        if let url = URL(string: "https://pincood.com/pincood/public/api/user/trips") {
            var request = URLRequest(url: url)
            request.allHTTPHeaderFields = [
                "Content-Type": "application/json",
                "Session": "fb4e7f9b-0f31-4709-",
                "AUthorization":"<some key>"
            ]
            
            URLSession.shared.dataTask(with: request) { (data, response, error) in
                guard error == nil else { return }
                guard let data = data else { return }
                do{
                    let codabledata = try JSONDecoder().decode([PastRide].self, from: data)
                    print(codabledata)
                    DispatchQueue.main.async {
                        self.past = codabledata
                        self.mTable.reloadData()
                    }
                } catch {
                    print(error)
                }
            }.resume()
        }
    }
}

扩展代码

extension PastTripsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return past.count
        print(past.count)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PastTableView
        cell.usernm.text = past[indexPath.row].provider.firstName
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let details : PastDetailView = self.storyboard?.instantiateViewController(withIdentifier: "PastDetailView") as! PastDetailView
        navigationController?.pushViewController(details, animated: true)
        
    }
}

排查与解决要点

  1. 修复数据源方法的代码错误
    numberOfRowsInSection中return past.count之后的print(past.count)永远不会执行,建议调整顺序,先打印再返回,方便确认数组元素数量:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(past.count)
        return past.count
    }
    
  2. 修正API请求头的拼写错误
    请求头中的AUthorization拼写错误,正确应为Authorization,这个错误可能导致API返回空数据或权限错误,修正后重新测试。

  3. 确保TableView的代理与数据源已绑定
    要么在viewDidLoad中添加代码绑定:

    mTable.delegate = self
    mTable.dataSource = self
    

    要么在Storyboard/XIB中将TableView的delegate和dataSource拖拽关联到ViewController,未绑定的话TableView不会触发数据源方法。

  4. 验证JSON解析正确性

    • 查看print(codabledata)的输出,确认解析后的数组是否有元素。如果为空,检查PastRide模型的属性名、类型是否与API返回的JSON字段完全匹配(注意大小写差异,比如JSON中的first_name需在模型中通过CodingKeys映射到firstName)。
    • 捕获解析错误时,打印完整错误信息,定位解析失败原因。
  5. 检查Cell的Outlet连接
    确认PastTableView中的usernm标签已正确连接到XIB中的UILabel,否则即使数据正确也无法显示。

  6. 处理可选值安全问题
    past[indexPath.row].provider.firstName可能为可选值,建议添加空值处理避免崩溃:

    cell.usernm.text = past[indexPath.row].provider.firstName ?? "未知"
    

内容的提问来源于stack exchange,提问作者Simran Bhavsar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:15:40