使用 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/