我尝试将存储在Firebase上的帖子加载到tableView中。我使用.childAdded函数按发布顺序(从头到尾)获取帖子。首先,它似乎可以工作,但是现在它不再起作用了,我也不知道为什么。因此,我在帖子中添加了时间戳,并使用了queryOrderedByChild(“ timestamp”)。仍然是错误的顺序!这是我的代码:
posts.removeAll()
let ref = FIRDatabase.database().reference()
ref.child("Posts").queryOrderedByChild("timestamp").observeEventType(.ChildAdded, withBlock: { (snapshot:FIRDataSnapshot) in
print(snapshot.value!["timestamp"] as! Int)
if snapshot.value == nil {
return
}
let post = Post()
post.title = snapshot.value!["Title"] as? String
post.postType = snapshot.value!["postType"] as? Int
post.postDescription = snapshot.value!["Description"] as? String
if post.postType == 2 {
post.imageAURL = snapshot.value!["imageAURL"] as? String
post.imageBURL = snapshot.value!["imageBURL"] as? String
}else if post.postType == 3 {
post.imageAURL = snapshot.value!["imageAURL"] as? String
post.imageBURL = snapshot.value!["imageBURL"] as? String
post.imageCURL = snapshot.value!["imageCURL"] as? String
}
let createdByID = snapshot.value!["createdBy"] as! String
var username = String()
let usernameRef = FIRDatabase.database().reference().child("users").child(createdByID)
usernameRef.observeSingleEventOfType(.Value, withBlock: { (snapshot:FIRDataSnapshot) in
username = snapshot.value!["username"] as! String
post.createdBy = username
self.posts.append(post)
self.tableView.reloadData()
}, withCancelBlock: nil)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}, withCancelBlock: nil)
}
查询开头的时间戳记值打印输出:
1471008028
1471007899
1471007928
1471007979
如您所见,第一个Int是最高的,接下来的三个是按升序正确排列的,但是为什么最高的是第一个而不是最后一个呢?我不知道它是否与它有任何关系,但是代码在内部称为viewDidLoad的函数中。
有一个现有的答案可以解释为什么Firebase JavaScriptchild_added
事件无序发生。它仍然适用,并且是按意外顺序交付快照的原因。
我知道这可能看起来很奇怪,但这实际上是预期的行为。
为了保证本地事件可以立即触发而无需先与服务器通信,Firebase不保证将始终按排序顺序调用child_added事件。
要将接收的快照按正确的顺序排列,您需要快照随附的先前的同级键(prevChildName
在参考答案中称为)。要获取上一个同级密钥,您需要使用observeEventType:andPreviousSiblingKeyWithBlock:
。
Firebase的文档observeEventType:andPreviousSiblingKeyWithBlock:
未明确说明应如何使用先前的同级密钥来安排接收到的快照。
出于示例目的,要在阵列中存储和排序快照,您需要对每个接收到的快照执行以下操作:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句