在UITableView中显示来自JSON的数据

时间:2019-04-01 08:28:40

标签: mysql json swift xcode uitableview

............................................... ................................................... ................................................... ................. 我得到数据并打印。也许代码是不正确的,但我还是很快,但是我在Xcode中没有任何错误。缺少一些东西,但我只是不知道。 导入UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    struct Class: Codable {

        let first_name: String
        let last_name: String
        let email: String

        enum CodingKeys: String, CodingKey {
            case first_name = "first_name"
            case last_name = "last_name"
            case email = "email"
        }
    }

    @IBOutlet weak var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://x.de/x.php")

        URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { print(error!); return }

            let decoder = JSONDecoder()
            let classes = try! decoder.decode([Class].self, from: data)



            for myClass in classes {
                print(myClass.first_name)
                print(myClass.last_name)
                print(myClass.email)
            }

        }
            ).resume()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableview.reloadData()
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return myarray.count
        return 1
    }

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

        return cell
    }

}

2 个答案:

答案 0 :(得分:1)

几个问题


  • 您的视图控制器缺少dataSource,它是一个保存用户列表的数组
  • 一旦接收到远程数据,就更新阵列(数据源)
  • 使用UITableView,在数组(数据源)更改后重新加载tableView.reloadData()
  • numberOfRowsInSection内返回数组元素dataSource.count的数量
  • UITableView.dequeueReusableCell(withIdentifier:for:)要求您使用tableview.register方法注册单元格类或xib
  • 最后,使用camelCase变量命名约定作为firstName,而不是下划线,作为first_name

struct User: Codable {
    let firstName: String
    let lastName: String
    let email: String

    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"
        case lastName = "last_name"
        case email = "email"
    }
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableview: UITableView!

    private var dataSource = [User]() {
        didSet {
            self.tableview.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableview.register(UITableViewCell.self, forCellReuseIdentifier: "groupCell")
        self.tableview.dataSource = self
        self.tableview.delegate = self

        let url = URL(string: "https://example.com/users.php")

        URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "An error occurred")
                return
            }

            // Within `dataTask` we are on background thread, we must update our UITableView on main thread
            DispatchQueue.main.async {
                self?.dataSource = try! JSONDecoder().decode([User].self, from: data)
            }
        }).resume()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableview.reloadData()
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath)
        let user = self.dataSource[indexPath.row]
        cell.textLabel?.text = user.firstName
        return cell
    }

}

以上代码会产生

enter image description here

答案 1 :(得分:0)

在cellForRowAt函数中,您必须执行以下操作:

cell.textLabel?.text = myarray[indexPath.row]

因为myarray的文本应显示在标签上或其他地方