首页 > 解决方案 > 拉动刷新不适用于表格视图

问题描述

我的视图控制器中有一个表格视图,我正在尝试实现拉动刷新功能。当我拉刷新表视图不会重新加载并且数据不会更新。

当我在 fetchRefresh 函数中打印数组 print(tempRefresh) 时,它返回一个空数组?

我的 firebase 数据库看起来像这样。

数据库

override func viewDidLoad() {
    super.viewDidLoad()

// refresh the page
    refreshControl = UIRefreshControl()
    if #available(iOS 10.0, *) {
        tableView.refreshControl = refreshControl
    } else {
        // fallback on older versions
        tableView.addSubview(refreshControl)
    }
    refreshControl.attributedTitle = NSAttributedString(string: "Loading...")
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)

// reload the tabelview
    tableView.reloadData()
    tableView.delegate = self
    tableView.dataSource = self

}

@objc func handleRefresh() {
print("refresh")
beginRefresh()
DispatchQueue.main.async {
    self.refreshControl.endRefreshing()
}
  }

func fetchRefresh(completion: @escaping(_ comments:[Comments])->()) {
    
    oldCommentsQuery.queryLimited(toLast: 20).observeSingleEvent(of: .value, with: { snapshot in
        var tempRefresh = [Comments]()
        let commentsSnap = snapshot.childSnapshot(forPath: "comments")
        let allComments = commentsSnap.children.allObjects as! [DataSnapshot]
        for commentSnap in allComments {
            let degree = commentSnap.childSnapshot(forPath: "reply degree").value as? String ?? ""
            let name = commentSnap.childSnapshot(forPath: "reply name").value as? String ?? ""
            let text = commentSnap.childSnapshot(forPath: "reply text").value as? String ?? ""
            let university = commentSnap.childSnapshot(forPath: "reply university").value as? String ?? ""
            let photoURL = commentSnap.childSnapshot(forPath: "reply url").value as? String ?? ""
            let url = URL(string: photoURL)
            let timestamp = commentSnap.childSnapshot(forPath: "timestamp").value as? Double
            let lastComment = self.comments.last
            
            if snapshot.key != lastComment?.id {
                
                let newRefresh = Comments(id: snapshot.key, fullname: name, commentText: text, university: university, degree: degree, photoURL: photoURL, url: url!, timestamp: timestamp!)
                
                tempRefresh.insert(newRefresh, at: 0)
                
                //test
                print(tempRefresh)
                
            }
        }
        return completion(tempRefresh)
    })
}

func beginRefresh() {
    
    fetchingMore = true
    // fetch the comments
    fetchRefresh { newComments in
        self.comments.append(contentsOf: newComments)
        self.endReached = newComments.count == 0
        self.fetchingMore = false
        self.tableView.reloadData()
    }
    
}

标签: swiftfirebase-realtime-databaseuirefreshcontrol

解决方案


推荐阅读