【问题标题】:Display callback array in UITableView, currently showing as emptyUITableView中显示回调数组,当前显示为空
【发布时间】:2020-02-27 11:29:03
【问题描述】:

我有一个函数,它连接到一个端点并返回一个JSON 结果,我将它保存到一个数组中并使用回调函数。一切似乎都配置正确。但是当模拟器运行时,表中没有显示任何数据。我不确定为什么?我的印象是我只需要运行 tableView.reloadData() 但这没有任何作用

class ViewConversionsTableViewController: UITableViewController {

    /* codesToConvert: The Country code and Country sent from the previous view used to connect to the endpoint
     * arraysToDisplay: The total list of countries and their corresponding values to be displayed
     */
    var codesToConvert = [String]()
    var arraysToDisplay = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        calculateRate(value: codesToConvert) {(structuredArray) in
            self.arraysToDisplay.append(contentsOf: structuredArray)
        }
        tableView.reloadData()
    }

    func calculateRate(value: [String], completionHandler: @escaping (_ structuredArray: [String])->()){

        var structuredArray = [String]()

        let url = URL(string: "domain.com")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let postString = "pairs=\(value[0] + value[2])&pairs=\(value[2]+value[0])"
        request.httpBody = postString.data(using: String.Encoding.utf8)

        let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
            do  {

                var arrayToSend = [String]()

                let jsonResult = try  JSONSerialization.jsonObject(with: data!)
                let results = jsonResult as! [String: Any]
                for values in results{
                    arrayToSend.append(values.key)
                    arrayToSend.append("\(values.value)")
                }
                arrayToSend.append(value[1])
                arrayToSend.append(value[3])

                // Structure the array to the required format
                structuredArray.append(arrayToSend[1] + " " + String(arrayToSend[0].prefix(3)))
                structuredArray.append(arrayToSend[4])
                structuredArray.append(arrayToSend[3])
                structuredArray.append(arrayToSend[5] + " · " + String(arrayToSend[2].prefix(3)))

                completionHandler(structuredArray)

            } catch {
                print(error)
            }
        }
        task.resume()
    }



    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ConversionsCell

        cell.Amount1.text = arraysToDisplay[0]
        cell.currencyName1.text = arraysToDisplay[1]
        cell.Amount2.text = arraysToDisplay[2]
        cell.currencyName2.text = arraysToDisplay[3]

        return cell
    }

}

【问题讨论】:

    标签: json swift uitableview


    【解决方案1】:

    您应该已经在完成块内重新加载了 tableview。

    override func viewDidLoad() {
       super.viewDidLoad()
       calculateRate(value: codesToConvert) {(structuredArray) in
          self.arraysToDisplay.append(contentsOf: structuredArray)
          DispatchQueue.main.async {
             tableView.reloadData()
          }
       }   
    }
    

    【讨论】:

    • 错误:UITableView.reloadData() 只能在主线程中使用,UITableViewController.tableView 只能在主线程中使用
    • 主线程检查器:在后台线程上调用 UI API:-[UITableViewController tableView] PID:99931,TID:3928363,线程名称:(无),队列名称:NSOperationQueue 0x7f7f9480d580(QOS:未指定) , 服务质量: 0
    • 完美!谢谢
    • 如果您觉得有帮助,您可以接受答案。干杯!
    【解决方案2】:

    这是因为您的tableView在数据网络调用过程尚未完成时加载数据。

    把你的 tableView.reloadData 放在闭包里,它必须在主线程上。所以应该是这样的:

    override func viewDidLoad() {
       super.viewDidLoad()
       calculateRate(value: codesToConvert) {(structuredArray) in
          self.arraysToDisplay.append(contentsOf: structuredArray)
    
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
       }   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多