从 Firebase 完成加载后如何使 UIRefreshControl 结束刷新
Posted
技术标签:
【中文标题】从 Firebase 完成加载后如何使 UIRefreshControl 结束刷新【英文标题】:How to make UIRefreshControl end refreshing when finish loading from Firebase 【发布时间】:2017-07-19 08:16:35 【问题描述】:以下方法是我的刷新数据方法。它将从 firebase 读取以获取最新数据。因为 firebase 是不同步的,所以我在 endRefreshing 之前等待 5 秒等待 Firebase 完成读取过程。
func refreshData()
//Remove old data
self.items.removeAll()
//Renew all data
var ref: DatabaseReference!
ref = Database.database().reference(withPath: "tasks")
//Loading local drafts
var drafts : [Task]!
if let local_drafts = NSKeyedUnarchiver.unarchiveObject(withFile: Task.ArchiveURL.path) as? [Task]
drafts = local_drafts
else
drafts = []
//Reloading the database
ref.observe(.value, with: snapshot in
var newItems: [Task] = []
self.num_of_tasks = Int(snapshot.childrenCount)
for item in snapshot.children
//let local = item as! DataSnapshot
//let snapshotValue = local.value as! [String: AnyObject]
//print(snapshotValue["main_content"] as! String!)
let taskItem = Task(snapshot: item as! DataSnapshot)
newItems.append(taskItem!)
let merged = drafts + newItems
self.items = merged
self.tableView.reloadData()
//Wait for 5 seconds
let deadlineTime = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute:
self.refreshControl!.endRefreshing()
)
)
但这不是一个好的解决方案,因为有时所有数据都加载了但刷新仍在继续,这很奇怪。有没有办法解决这种情况?让 refreshControl 结束刷新,直到我从 firebase 加载所有数据?
【问题讨论】:
【参考方案1】:下面是一种方法。它会一直等到异步数据下载完成,当completionHandler返回true或false时,refreshControl将停止刷新。我这里没有编译器,所以我希望它能正常工作。
func viewDidLoad()
refreshData _ in
self.refreshControl!.endRefreshing()
func refreshData(completionHandler:@escaping (Bool)->() )
//Remove old data
self.items.removeAll()
//Renew all data
var ref: DatabaseReference!
ref = Database.database().reference(withPath: "tasks")
//Loading local drafts
var drafts : [Task]!
if let local_drafts = NSKeyedUnarchiver.unarchiveObject(withFile: Task.ArchiveURL.path) as? [Task]
drafts = local_drafts
else
drafts = []
//Reloading the database
ref.observe(.value, with: snapshot in
var newItems: [Task] = []
self.num_of_tasks = Int(snapshot.childrenCount)
for item in snapshot.children
//let local = item as! DataSnapshot
//let snapshotValue = local.value as! [String: AnyObject]
//print(snapshotValue["main_content"] as! String!)
let taskItem = Task(snapshot: item as! DataSnapshot)
newItems.append(taskItem!)
let merged = drafts + newItems
self.items = merged
self.tableView.reloadData()
completionHandler(true)
)
【讨论】:
我看过几篇关于completionHandler的帖子,但是当我使用它时,它会说“未定义的标识符”。这是一个内置类吗? @WanhuiQiao,不,这个解决方案应该可以工作......你从哪里得到这个错误? 唯一的错误是“使用未解析的标识符completionHandler”。 @WanhuiQiao 哎呀,把参数改成completionHandler,我编辑代码 我有另一个错误“对以上是关于从 Firebase 完成加载后如何使 UIRefreshControl 结束刷新的主要内容,如果未能解决你的问题,请参考以下文章
Vue.js:从 Firebase 存储中检索数据后如何异步加载模板?