【发布时间】:2017-08-27 21:31:55
【问题描述】:
我已经如图所示设置了我的火力基地,现在我想通过比较每个帖子的时间戳来只为我的帖子提供新帖子,我已经编写了下面的代码
func getRecentPosts(start timestamp: Int? = nil, limit: UInt, completionHandler: @escaping (([Post]) -> Void)){
let POST_DB_REF: DatabaseReference = Database.database().reference().child("posts")
var allPosts = POST_DB_REF.queryOrdered(byChild: "timestamp")
if let latestPostTimestamp = timestamp, latestPostTimestamp > 0 {
//If the timestamp is specified, we will get the posts with timestamp newer than the given value
allPosts = allPosts.queryStarting(atValue: latestPostTimestamp + 1, childKey: Post.PostInfoKey.timestamp).queryLimited(toLast: limit)
} else {
//Otherwise, we will just get the most recent posts
allPosts = allPosts.queryLimited(toLast: limit)
}
//Call Firebase API to retrieve the latest records
allPosts.observeSingleEvent(of: .value, with: { (snapshot) in
var newPosts: [Post] = []
for userPosts in snapshot.children.allObjects as! [DataSnapshot] {
for eachPost in userPosts.children.allObjects as! [DataSnapshot] {
let postInfo = eachPost.value as? [String:Any] ?? [:]
if let post = Post(postId: eachPost.key, postInfo: postInfo) {
newPosts.append(post)
}
}
}
if newPosts.count > 0 {
//Order in descending order (i.e. the latest post becomes the first post)
newPosts.sort(by: {$0.timestamp > $1.timestamp})
}
completionHandler(newPosts)
})
}
这是我的 Firebase 配置。 FIREBASE 这适用于第一次运行,然后如果我发布一个新的提要它不会得到更新,有什么想法吗? 提前致谢。
【问题讨论】:
-
getRecentPosts 是如何被调用的?错误可能是没有调用此方法吗?
-
是的,我在我的 FeedTableViewController 中调用此方法,并在其中添加新帖子。
-
实际上,它是通过两种方法调用的,在 ViewDidLoad 和每当我发布内容时。
标签: ios firebase swift3 firebase-realtime-database