您如何按时间顺序正确地从 Firebase 中订购数据 [英] How do you properly order data from Firebase chronologically
问题描述
我正在尝试从 Firebase 订购我的数据,因此最近的帖子位于顶部(如 Instagram),但我无法使其正常工作.我应该使用服务器时间戳吗?是否有createdAt"字段?
I'm trying to order my data from Firebase so the most recent post is at the top (like Instagram), but I just can't get it to work properly. Should I be using a server timestamp? Is there a "createdAt" field?
func getPosts() {
POST_REF.observeEventType(.Value, withBlock: { snapshot in
guard let posts = snapshot.value as? [String : [String : String]] else {
print("No Posts Found")
return
}
Post.feed?.removeAll()
for (postID, post) in posts {
let newPost = Post.initWithPostID(postID, postDict: post)!
Post.feed?.append(newPost)
}
Post.feed? = (Post.feed?.reverse())!
self.tableView.reloadData()
}, withCancelBlock: { error in
print(error.localizedDescription)
})
}
推荐答案
仅对数组使用 reverse() 不足以涵盖所有内容.您需要考虑不同的事情:
Using only reverse() for your array is not enough way to encompass everything. There are different things you need to think about:
在检索数据时限制,使用 append() 和 reverse() 以节省时间.您不需要每次都删除所有数组.
Limit while retrieving data, use append() and then reverse() to save time. You don't need to delete all array for each time.
滚动触发器或willDisplay单元格方法加载
让我们开始吧.您可以为您的帖子创建一个子时间戳或日期/时间全局.为了提供类似 Instagram 秒、周的时间,我建议您使用 UTC 时间.所以我称之为:(timeUTC)
Let's start. You can create a child for your posts timestamp or date/time being global. To provide like Instagram seconds, weeks I advice you using UTC time. So I will call this: (timeUTC)
要对所有帖子进行排序,请使用 since1970 时间戳.所以我将称之为 (timestamp) 然后你也可以保留另一个节点作为 (reversedTimestamp) 添加 - 前缀到时间戳.所以当你使用 queryOrdered 到这个节点时.您可以使用 yourQuery.queryLimited(toFirst: 5)
处理最新的 5 个帖子.
For sorting your all post, use since1970 timestamp. So I will call this (timestamp) and then also you can keep another node as (reversedTimestamp) adding - prefix to timestamp. So when you use queryOrdered to this node. You can handle latest 5 post using with yourQuery.queryLimited(toFirst: 5)
.
1.获取 Swift 3 中 timeUTC 节点的 UTC 日期/时间:
let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = TimeZone(abbreviation: "UTC")
let utcTimeZoneStr = formatter.string(from: date)
+0000 表示它是世界时,看看 http://time.is/tr/UTC
+0000 means it's universal time, look at http://time.is/tr/UTC
2. 获取 1970 年以来的时间戳,以便在 Swift 3 中对帖子进行排序:
let timestamp = (Date().timeIntervalSince1970 as NSString).doubleValue
let reversedTimestamp = -1.0 * timestamp
现在,您可以像这样将它们保存在 Firebase 帖子中.
Now, you can save them on your Firebase posts like this.
"posts" : {
"-KHLOy5mOSq0SeB7GBXv" : {
"timestamp": "1475858019.2306"
"timeUTC" : "2012-02-04 12:11:56 +0000"
},
"-KHLrapS0wbjqPP5ZSUY" : {
"timestamp": "1475858010.1245"
"timeUTC" : "2014-02-04 12:11:56 +0000"
},
我将检索 5 个 5 个帖子,所以我在 viewDidLoad
中执行 queryLimited(toFirst: 5):
I will retrieve five by five post, so I'm doing queryLimited(toFirst: 5) in viewDidLoad
:
let yourQuery = ...queryOrdered(byChild: "reverseTimestamp")
.queryEnding(atValue: "(self.pageOnTimestamp)", childKey: "reverseTimestamp")
yourQuery.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull {
print("There is no post.")
}
else {
yourQuery.queryLimited(toFirst: 5).observeSingleEvent(of: .value, with: { (snapshot) in
self.posts.removeAll(keepingCapacity: true)
for (i, snap) in snapshot.children.enumerated() {
if let postAllDict = snapshot.value as? [String: AnyObject] {
if let postDict = postAllDict[(snap as AnyObject).key as String] as? [String: AnyObject] {
let post = Post(key: (snap as AnyObject).key as String, postDict: postDict)
self.posts.append(post)
}
}
}
completion(true)
})
}
})
如果用户到达了最新的帖子,您可以使用如下的willDisplay
方法处理它,然后您可以调用loadMore函数.
If user reached latest post, you can handle it with willDisplay
method like below, then you can call loadMore function.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if self.posts.count - 1 == indexPath.row {
// call loadMore function.
}
}
在 loadMore() 函数中,您可以处理最新帖子的时间戳,然后开始-结束查询,这样您就可以轻松地继续下前 5 个帖子,同时追加到数组之前.
In loadMore() function you can handle latest post's timestamp, then start-end query as with that, so you can easily continue with next first 5 posts while appending before array.
对于格式良好的 Swift 3 转换,请查看此处:Swift 3 - UTC 到时间前标签,思考 12h/24h 设备时间变化
For Swift 3 conversion as nice formatted, take a look here: Swift 3 - UTC to time ago label, thinking 12h / 24h device time changes
这篇关于您如何按时间顺序正确地从 Firebase 中订购数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!