How to reloadData for tableview after data been pr

2019-01-20 06:46发布

I use URLSession to get data from a resource API for tableview'data. So I need to reloadData() after data prepared by the URLSession task. But this will lead to,

UITableView.reloadData() must be used from main thread only

And when I run the app, at begin the tableview is blank. Only after I croll the screen the data will show. But if not call reloadData() in the URLSession task, the screen is blank all the way.

func getData() {
    let dataUrl = URL(string: "http://www.example.com/app/?json=1")
    let task = URLSession.shared.dataTask(with: dataUrl! as URL) {data, response, error in
        guard let data = data, error == nil else { return }
        do {
            self.data = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
            self.tableView.reloadData()
            }

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

4条回答
三岁会撩人
2楼-- · 2019-01-20 07:24

You should never access any UI from background threads, you must do it from the main thread, to do this you may use gcd:

DispatchQueue.main.async {
    self.tableView.reloadData()
}

While accessing UI (read everything UIKit) from background thread may work sometimes, you'll end up with bugs including crashes, blown up display or gazenbugs.

查看更多
时光不老,我们不散
3楼-- · 2019-01-20 07:28

Try this

func getData() {
let dataUrl = URL(string: "http://www.example.com/app/?json=1")
let task = URLSession.shared.dataTask(with: dataUrl! as URL) {data, response, error in
    guard let data = data, error == nil else { return }
    do {
        self.data = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
       DispatchQueue.main.async {
           self.tableView.reloadData()
        }
        }

    } catch let error {
        print(error)
    }
}
task.resume()
}
查看更多
Juvenile、少年°
4楼-- · 2019-01-20 07:29

You can't do any UI update operation in background thread. So can put it in main thread.

DispatchQueue.main.async {
    tableView.reloadData()
}

If you try to perform UI operation in background thread it will cause crash.

查看更多
够拽才男人
5楼-- · 2019-01-20 07:36

The best way to Update UI Views .. Use main queue.

DispatchQueue.main.async(execute: {
  yourTableView.reloadData()
})

I hope it will work.

查看更多
登录 后发表回答