我正在使用refreshcontrol,但是在编译代码时,当前代码存在一个问题,即它先删除所有数据,然后再提取表数据,这会导致片刻不显示任何数据的情况。有快速解决方案吗?编辑:我已经在下面添加了fetchNetworkPost的相关部分。
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(requestData), for: .valueChanged)
self.refreshControl = refreshControl
requestData()
}
@objc
func requestData() {
self.postArray.removeAll()
fetchNetworkPosts() //populates data
refresh()
}
func refresh() {
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
func fetchNetworkPosts() {
for personId in networkArray {
let currentUserRef =
Database.database().reference().child("posts").queryOrdered(byChild:
"userId").queryEqual(toValue: personId)
currentUserRef.observeSingleEvent(of: .value, with: {
(snapshot) in
for childSnapshot in snapshot.children {
let test = Post(snapshot: childSnapshot as! DataSnapshot)
self.postArray.append(test)
}
self.postArray.sort { $0.postDate > $1.postDate } //sort
self.tableView.reloadData()
})
}
}
也许更改顺序会解决您的问题。
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(requestData), for: .valueChanged)
self.refreshControl = refreshControl
requestData()
}
@objc
func requestData() {
fetchNetworkPosts() //populates data
refresh()
}
func refresh() {
self.postArray.removeAll()
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
您正在提取数据,然后将其删除。因此,首先获取数据,然后删除tableView。您会在短时间内看到旧数据,而不是空的tableView。
@objc
func requestData() {
// dont remove data here, just call api for new data
fetchNetworkPosts() //populates data
refresh()
}
内部fetchNetworkPosts()
方法,当您收到新数据时self.postArray.removeAll()
在那里删除旧数据,然后分配新值。希望这对您有用。
在完成fetchNetworkPosts()之后调用您的refresh(),如下所示。检查下面的代码。
@objc func requestData() {
fetchNetworkPosts() //populates data
}
func refresh() {
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
func fetchNetworkPosts() {
for personId in networkArray {
let currentUserRef =
Database.database().reference().child("posts").queryOrdered(byChild:
"userId").queryEqual(toValue: personId)
currentUserRef.observeSingleEvent(of: .value, with: {
(snapshot) in
self.postArray.removeAll()
for childSnapshot in snapshot.children {
let test = Post(snapshot: childSnapshot as! DataSnapshot)
self.postArray.append(test)
}
self.postArray.sort { $0.postDate > $1.postDate } //sort
self.refresh()
})
}
}