Ios 如何重新加载tableview';在JSON数据下载后,重新设置数据

Ios 如何重新加载tableview';在JSON数据下载后,重新设置数据,ios,swift,uitableview,Ios,Swift,Uitableview,我在func viewDidLoad()中调用getPrizesData 下载完JSON数据后,我调用reload 但它没有刷新我在tableview中的单元格 如何修复它?谢谢 @IBOutlet var invoice: UITableView! func getPrizesData()-> Void{ let url = NSURL(string: "http://localhost:3002/invoices.json") let sharedSession =

我在
func viewDidLoad()中调用
getPrizesData

下载完JSON数据后,我调用
reload

但它没有刷新我在tableview中的单元格

如何修复它?谢谢

@IBOutlet var invoice: UITableView!

func getPrizesData()-> Void{
    let url = NSURL(string: "http://localhost:3002/invoices.json")
    let sharedSession = NSURLSession.sharedSession()
    let downloadTask: NSURLSessionDownloadTask =
    sharedSession.downloadTaskWithURL(url,
        completionHandler: {(location: NSURL!, response: NSURLResponse!, error: NSError!)->Void in
            if (error == nil){
                let dataObject = NSData(contentsOfURL: location)
                if let prizes = NSJSONSerialization.JSONObjectWithData(dataObject, options: .MutableLeaves, error: nil) as? NSArray {
                    let prizesDictionary = prizes[0] as NSDictionary
                    let toPrizesArray = prizesDictionary["to_prizes"] as NSArray
                    self.items = toPrizesArray as [AnyObject] as [String]
                    self.invoice.reloadData()
                }
                else {
                    println("error")
                }
            }else{

                println(error)
            }

    })
    downloadTask.resume()
}

数据在非主线程上下载。UI只能从主线程更新

dispatch_async(dispatch_get_main_queue()) {
    self.invoice.reloadData()
}

downloadTaskWithURL
方法在后台线程上调用其完成处理程序。所有UI更新(如重新加载tableView数据)都必须在主线程上执行。当数据准备就绪时,可以使用GCD在主线程上更新tableView。例如

 dispatch_async(dispatch_get_main_queue(), {
      self.invoice.reloadData()
 })

Swift 3更新 您只能在主队列上更新UI

1.用于异步获取主队列

DispatchQueue.main.async {                                        
    //code for updating the UI 
 }
DispatchQueue.main.sync{                                         
//code for updating the UI 
 } 
2.用于同步获取主队列

DispatchQueue.main.async {                                        
    //code for updating the UI 
 }
DispatchQueue.main.sync{                                         
//code for updating the UI 
 } 

您必须在主线程上更新ui,因此请使用以下代码:

DispatchQueue.main.async {
    self.invoice.reloadData()
}
注:适用于swift 5