Pull to Refresh:数据刷新延迟

Pull to Refresh: data refresh is delayed

我的 Pull to Refresh 工作得很好,除了当 table 重新加载时 table 中的数据重新加载之前有一个瞬间延迟。

我只是有什么地方不对劲吗?有什么想法吗?

viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
    self.getCloudKit()
}

handleRefresh 用于下拉刷新:

func handleRefresh(refreshControl: UIRefreshControl) {    
    self.objects.removeAll()
    self.getCloudKit()
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        refreshControl.endRefreshing()
    })
}

需要两个地方的数据,所以为它创建了一个函数getCloudKit:

func getCloudKit() {
    publicData.performQuery(query, inZoneWithID: nil) { results, error in
        if error == nil { // There is no error
            for play in results! {
                let newPlay = Play()
                newPlay.color = play["Color"] as! String
                self.objects.append(newPlay)
            }

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.reloadData()
            })

        } else {
            print(error)
        }
    }
}

tableView:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
    let object = objects[indexPath.row]
    if let label = cell.textLabel{
        label.text = object.matchup
    }
    return cell
}

您应该这样做:

  1. 在您的 handleRefresh 函数中,添加一个布尔值来跟踪正在进行的刷新操作 - 例如 isLoading
  2. 在您的 getCloudKit 函数中,如果 isLoading 为真,则在重新加载 table 视图之前调用 endRefreshing 函数。
  3. isLoading 重置为 false
  4. 重要 - 在刷新操作甚至实例化之前不要删除模型数据。获取数据出错怎么办?只有在 getCloudKit 函数中得到响应后才删除它。
  5. 此外,作为旁注,如果我愿意的话,我会实施基于时间戳的方法,我会将我的最后一个服务数据时间戳(最后一次从服务器获取更新的时间)传递给服务器,服务器端会return 我的完整数据只有时间戳有变化 post 否则我希望他们告诉我没有变化。在这种情况下,我会简单地调用 endRefreshing 函数并且不会在 table 上重新加载数据。相信我 - 这节省了很多,并提供了良好的最终用户体验,因为大多数时候数据没有变化!