簡體   English   中英

JSON數據下載后如何重新加載tableview的數據

[英]How to reload tableview's data after JSON data has downloaded

我在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 
 }

2.同步獲取主隊列

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

您必須在主線程上更新 ui,因此使用以下代碼:

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

注意:適用於 swift 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM