【问题标题】:Swift3: Populate UITableView with data from External database?Swift3:使用外部数据库中的数据填充 UITableView?
【发布时间】:2017-06-27 06:16:55
【问题描述】:

我正在尝试使用来自外部数据库的一些数据加载 UItable。我能够在输出面板中打印所需的数据,但无法在 tableview 上获取数据。我怎样才能解决这个问题?

代码:

    import UIKit

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    //let myarray = ["item1", "item2", "item3"]



    var group = [Group]()

    @IBOutlet weak var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://www.myurl/myfile.php")

        let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in

            guard let data = data, error == nil else { return }

            print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
        }

        task.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
       // cell.textLabel?.text = myarray[indexPath.item]
        return cell
    }

}

【问题讨论】:

    标签: uitableview swift3 nsurlsession


    【解决方案1】:

    Tableview 在接收数据之前重新加载。完成任务后需要重新加载表格视图。

    let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in
    
    guard let data = data, error == nil else { return }
    
    print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
    
    //Store into your array depend on response.
    DispatchQueue.main.async() {
        self.tableView.reloadData()
    } } task.resume()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2019-05-20
      • 2016-01-20
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      相关资源
      最近更新 更多