【发布时间】:2019-01-28 19:17:03
【问题描述】:
我无法从 firebase 观察当前数据,然后将该数据加 1 并将其写回 firebase;但我目前的代码似乎是一个永无止境的循环
func likevideoFirebase(row : Int){
let videoKey = instanceOfUser.myVideos[instanceOfUser.indexNumber].videoKey
let ref = Database.database().reference()
let userKey = instanceOfUser.myVideos
ref.child("Vidpost").child(videoKey).child("video").child(userKey).child("like").child("count").observe(.value) { (snapshot) in
var value = snapshot.value as? Int ?? 0
value += 1; self.instanceOfUser.myVideos[self.instanceOfUser.indexNumber].sentVideo[row].like.numberOfLike = value
// this where I set the data I received add 1 to it and use the function below to add it to firebase , but instead it ends up a being a never ending loop
self.setliketofirebase(like: value, row: row)
}
}
func setliketofirebase(like : Int ,row : Int ){
let videoKey = instanceOfUser.myVideos[instanceOfUser.indexNumber]
let ref = Database.database().reference()
guard let userKey = Auth.auth().currentUser?.uid else {return}
ref.child("Vidpost").child(videoKey).child("video").child(userKey).child("like").child("count").setValue(like)
}
【问题讨论】:
-
由于您只执行此操作一次,请使用 .observeSingleEvent 读取它。 .value 在节点上留下一个观察者,每次更新时,关闭代码都会触发(一遍又一遍)。此外,您可能希望构建 ref 并从中读取,然后在同一个闭包中写入它 - 它可能比仅用于一行代码的单独函数更干净。 (无论哪种方式都可以,只是试图简化)
标签: swift loops firebase firebase-realtime-database observers