1

So I'm trying to parse some JSON data retrieved from a server and display it nicely in a table, ive followed the suggestions here: UITableView example for Swift and managed to get the example working.

However with the data im parsing the table remains blank. Can anyone see where im going wrong?

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).")

        }
Community
  • 1
  • 1
CS456
  • 109
  • 11

1 Answers1

2

Data is not displaying because you didn't reload the table view after you append the items array. Please reload the table view at the end of task closure

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