【发布时间】:2016-12-19 13:14:31
【问题描述】:
我尝试将存储在 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 内部调用的函数内。
【问题讨论】:
-
我发布了来自不同用户帐户的帖子。我刚刚注意到,当前登录的用户的帖子总是最先加载的,但是为什么呢?意味着如果我以其他用户身份登录并再次启动模拟器,则顺序会更改,但 .ChildAdded 函数不应该关心登录的用户,因为它只会加载所有帖子,无论是谁发布的?
-
这已被问及回答before。
-
我猜这个答案有点过时了,如果我错了,请纠正我。 swift中也没有示例,所以如果有人在swift中有一些解决方案或者可以编辑我的代码以便按照它应该的方式工作,那就太好了
-
我也不明白为什么按时间戳排序似乎不起作用
-
能否请您使用 Firebase 结构的 sn-p 作为文本更新您的问题,不要使用图像。
标签: ios database swift firebase firebase-realtime-database