ios - 使用observeSingleEvent/snapshot,如何编写一行代码来检查用户是否在过去24小时内向数据库添加了子条目?

标签 ios swift xcode firebase

使用 if (snapshot.exists()){ 很简单,但如何修改它以仅包含过去 24 小时内创建的数据库条目的快照?

///如果您只检查用户是否有快照,这就是它的样子。您想要的是检查快照是否是在 24 小时内创建的。

super.viewDidAppear(animated)

    let databaseRef = Database.database().reference()
    let uid = Auth.auth().currentUser!.uid
    databaseRef.child("users").child(uid).child("Photos").observeSingleEvent(of: .value, with: { (snapshot) in

        if (snapshot.exists()){

            print ("good")            }

        else{

            self.performSegue(withIdentifier: "toVegas", sender: nil)

        }


    })

如果快照方法不起作用,我在想也许某些网站告诉你不能在x分钟内发帖的方式可以反向使用(即performSegue,如果他们没有在 x 分钟/小时内发布)。

最佳答案

一种方法是在创建子节点时使用 ServerValue.timestamp() 作为额外参数,完成后,您可以比较检索到的快照的时间戳并做出你所说的24小时延时的验证

这是一个示例函数,说明如何修改数据库的写入方法以包含时间戳

func sendMessage() {
    let data = ["UserName": userName,
                "message" : message,
                "timestamp": ServerValue.timestamp()]

    Database.database().reference().child("Photos").setValue(data)
}

然后在你的观察者中你可以做这样的事情

 databaseRef.child("users")
    .child(uid)
    .child("Photos")
    .observeSingleEvent(of: .value, with: { (snapshot) in

    guard let message = snapshot.value as? [String:String] else { return }

    let timestamp = message["timestamp"] as! UInt64
    //TODO - Look up how to convert that value to a date, once you get that done you can compare that date to a constant date of 24hrs and decide what to do next in your code

    if (snapshot.exists()){

        print ("good")            
     }else{

        self.performSegue(withIdentifier: "toVegas", sender: nil)

    }


})

关于ios - 使用observeSingleEvent/snapshot,如何编写一行代码来检查用户是否在过去24小时内向数据库添加了子条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57009093/

相关文章:

ios - 我希望使用输入/返回按钮和我的 UITextField 触发事件

ios - 在 Swift 中重试 firebase token

objective-c - 在 Swift 中使用 PDFKIT 搜索 PDF

ios - 如何在 Firebase 中设置属性?

iphone - 自动发送消息和邮件?

objective-c - 为什么我的向下钻取应用程序崩溃了?

javascript - WKWebView 返回(_ :) evaluateJavaScript Fails if going back more than 2 in history

ios - PROD 和 STAGING 中适用于 iOS 的 Google 跟踪代码管理器容器设置

swift - 如何从特定索引处的字典中删除对 - Swift?

ios - VLC iOS 编译不工作