刷新tableView在重新加载数据时闪烁

时间:2017-04-25 10:23:30

标签: ios swift uitableview refresh indexoutofrangeexception

因为索引超出范围问题,刷新功能一直使我的应用程序崩溃。我在第一次清空列表后添加了reloadData。现在我在刷新时会出现这种闪烁,因为它首先加载空列表然后加载填充列表。我应该在哪里清空列表,或者如何摆脱闪烁?我使用swift 3和Xcode 8.2.1

func getData()
{
    fetchedUsers.removeAll()
    self.userTableView.reloadData()

    //myphpfileurl
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in

        if (error != nil) {
            print("Error")
        }
        else{
            do{
                let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray

                for eachFetchedUsers in fetchedData {
                    let eachUsers = eachFetchedUsers as! [String : Any]
                    let id = eachUsers["id"] as! String
                    let name = eachUsers["Nimi"] as! String
                    let email = eachUsers["Sahkoposti"] as! String
                    let company = eachUsers["Yritys"] as! String

                    self.fetchedUsers.append(Users(id : id, name: name, email : email, company: company))

                }
                self.userTableView.reloadData()
                self.refreshControl.endRefreshing()
            }
            catch{
                print("Error 2")
            }
        }
    }
    task.resume()
}

1 个答案:

答案 0 :(得分:0)

尝试这样重新加载表格

DispatchQueue.main.async {
      self.userTableView.reloadData() 
      self.refreshControl.endRefreshing()
  }