如何在Firestore中筛选并仅展示24小时内创建的Story帖子
实现24小时内Story帖子的筛选
你可以通过在Firestore查询中添加时间范围筛选条件来实现只获取24小时内发布的帖子,具体实现如下:
核心思路
先计算当前时间往前推24小时的时间节点,再通过Firestore的查询条件,只返回timestamp大于等于该节点的帖子,全程在服务器端完成筛选,比客户端过滤更高效。
修改后的完整代码
func fetchStories(completion: @escaping([Story]) -> Void) { // 计算24小时前的时间,转成Firestore兼容的Timestamp类型 let twentyFourHoursAgo = Date().addingTimeInterval(-24 * 60 * 60) let timestampThreshold = Timestamp(date: twentyFourHoursAgo) Firestore.firestore().collection("stories") .whereField("timestamp", isGreaterThanOrEqualTo: timestampThreshold) .order(by: "timestamp", descending: true) .getDocuments { snapshot, _ in guard let documents = snapshot?.documents else { return } let stories = documents.compactMap({ try? $0.data(as: Story.self) }) completion(stories) } }
注意点
- 如果Firestore控制台提示需要创建复合索引,直接按照提示的链接完成创建即可(因为同时使用了
whereField和order(by)查询条件)。 - 你的
Story模型中timestamp字段已经是Firestore的Timestamp类型,和数据库字段类型完全匹配,无需额外转换。
内容的提问来源于stack exchange,提问作者robowarrior
相关产品推荐
相关产品推荐

