【问题标题】:Need some help populating tableview with JSON data after POST request在 POST 请求后需要一些帮助使用 JSON 数据填充 tableview
【发布时间】:2019-06-06 19:13:32
【问题描述】:

基本上,一旦发出 POST 请求并且 API 以 JSON 响应,我需要在 tableview 中显示 JSON 数据。

我没有收到任何错误,但我也没有收到任何显示在调试器中的 JSON 响应。我不确定到底出了什么问题,但表格视图中似乎没有加载或显示任何内容。

以下是我用来解释 JSON 的结构:

import UIKit

struct ScheduleStructure: Codable {
    let customer: String
    let PickedUpNUM: String
    let DeliveryNUM: String

}

这就是 JSON 的样子:

[
    {
        "customer": “Example”,
        "PickedUpNUM": “2”,
        "DeliveryNUM": “4”
    }
]

这是当前的tableview控制器:

import UIKit



class ScheduleCell: UITableViewCell {
    @IBOutlet weak var cellStructure: UIView!
    @IBOutlet weak var testingCell: UILabel!
    @IBOutlet weak var pickupLabel: UILabel!
    @IBOutlet weak var deliveryLabel: UILabel!
}

class ScheduleTableViewController: UITableViewController {

    var driverName = UserDefaults.standard.string(forKey: "name")!


    var structure = [ScheduleStructure]()

    override func viewDidLoad() {
        super.viewDidLoad()
    UINavigationBar.appearance().isTranslucent = false

        self.view.backgroundColor = UIColor.white


        //Adds Shadow below navigation bar
        self.navigationController?.navigationBar.layer.masksToBounds = false
        self.navigationController?.navigationBar.layer.shadowColor = UIColor.lightGray.cgColor
        self.navigationController?.navigationBar.layer.shadowOpacity = 0.8
        self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 2.0)
        self.navigationController?.navigationBar.layer.shadowRadius = 2


        self.extendedLayoutIncludesOpaqueBars = true
        fetchJSON()
        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)
        tableView.refreshControl = refreshControl

    }



    private func fetchJSON() {
        guard
            let url = URL(string: "https://example.com/example/example.php"),
            let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
            else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "value=\(value)".data(using: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, error in
            DispatchQueue.main.async {
                //
            }
            }.resume()

    }

    @objc func doSomething(refreshControl: UIRefreshControl) {
        print("reloaded")

        fetchJSON()

    }



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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "customerID", for: indexPath) as! ScheduleCell



        cell.textLabel?.font = .boldSystemFont(ofSize: 18)
        cell.textLabel?.textColor = UIColor.red

        let portfolio = structure[indexPath.row]

        cell.textLabel?.text = portfolio.customer


        return cell

    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


        let cell = tableView.dequeueReusableCell(withIdentifier: "customerID", for: indexPath) as! ScheduleCell
        //cell.cellStructure.layer.cornerRadius = 50
        let portfolio = structure[indexPath.row]


        let navigationController = UINavigationController(rootViewController: controller)

        self.present(navigationController, animated: true, completion: nil)

    }


    override func viewWillAppear(_ animated: Bool) {
        fetchJSON()

    }



}

如果有更好的方法,请告诉我

我只需要做一个 JSON POST 并将结果显示在一个表格中。

【问题讨论】:

  • 首先,你必须检查你是否真的可以得到响应数据,并在控制台上打印出来。
  • 以小写字母开头的属性名称并使用enum CodingKeys 来完成或更改返回的响应
  • 知道了,谢谢。你的回复真的帮助了我

标签: json swift uitableview


【解决方案1】:

您需要将 json 响应解码为 api 回调中的数组

URLSession.shared.dataTask(with: request) { data, _, error in 
       guard let data = data else { return }
       do {
         self.structure = try JSONDecoder().decode([ScheduleStructure].self,from:data)
          DispatchQueue.main.async {
           self.tableView.reloadData()
          }
        }
        catch {
          print(error)
        } 

}.resume()

struct ScheduleStructure: Codable {
    let customer, pickedUpNUM, deliveryNUM: String

    enum CodingKeys: String, CodingKey {
        case customer
        case pickedUpNUM = "PickedUpNUM"
        case deliveryNUM = "DeliveryNUM"
    }
}

【讨论】:

【解决方案2】:

我假设您知道dataTask 的正文实际上并没有对它接收到的数据做任何事情?里面只有一个空评论。

我猜你会想做这样的事情:

if let data = data {
    do {
        self.structure = try JSONDecoder().decode(Array<ScheduleStructure>.self, from: data)
        self.reloadData()
    } catch {
        print("TODO: handle parse error: \(error)")
    }
} else {
    print("TODO: handle network error: \(error)")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    相关资源
    最近更新 更多