为什么这些数据不会显示在我的Swift 3表中

时间:2017-03-28 15:58:53

标签: ios swift uitableview

所以我试图解析从服务器检索到的一些JSON数据并在表格中很好地显示它,我按照这里的建议:UITableView example for Swift并设法使示例正常工作。

然而,使用数据解析表仍然是空白。 任何人都可以看到我出错的地方?

import UIKit
import SwiftyJSON

class LogsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

 let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]

    var arrayCount:Int = 0

        struct Item {
            let name : String
            let lockTime : String
            let type : String
        }
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"

    var items = [Item]()

    @IBOutlet weak var textUodate: UIStackView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        tableView.delegate = self
        tableView.dataSource = self

        // Do any additional setup after loading the view.
        let lockid = UserDefaults.standard.value(forKey: "LockID")!
        //   let email = UserDefaults.standard.value(forKey: "email")!


        //get the data from the server for that specific lock id

        let u = UserDefaults.standard.value(forKey: "userIP")!
        var request = URLRequest(url: URL(string: "http://\(u):3000/logs")!)
        request.httpMethod = "POST"
        let postString = "LockID=\(lockid)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                              print("error=\(error)")
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
                print(response ?? " ")
            }
            let responseString = String(data: data, encoding: .utf8)

            if let data = responseString?.data(using: String.Encoding.utf8) {
                let resString = JSON(data: data)

                if resString["success"].stringValue == "true"
                {
                    self.arrayCount = (resString["message"].count)
                    print(self.arrayCount)
                    let returnedArray = resString["message"].arrayValue
                    for item in returnedArray {
                        let name = String(describing: item["name"])
                        let lockTime = String(describing: item["lockTime"])
                        let type = String(describing: item["type"])
                        self.items.append(Item(name:name, lockTime:lockTime, type:type))
                    }
                }
                else if resString["success"].stringValue == "false"
                {
                    print(resString["success"].stringValue)
                }

            }

        }
        task.resume()
        DispatchQueue.main.async{
            self.tableView.reloadData()
        }
    }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return arrayCount
    }
        // create a cell for each table view row
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

            let item = items[indexPath.row]

           let cellText = "\(item.name) \(item.type) At:  \(item.lockTime) "


           cell.textLabel?.text = cellText

            print(cellText)
            return cell

        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("You tapped cell number \(indexPath.row).")

        }

1 个答案:

答案 0 :(得分:2)

数据未显示,因为您在追加items数组后没有重新加载表视图。请在任务结束时重新加载表视图

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    // ......
    // ......
    self.tableView.reloadData()
}