How observe then write from firebase database consecutively swift

时间:2018-08-22 13:47:05

标签: swift loops firebase firebase-realtime-database observers

I am having trouble observing the current data from firebase, and then take that data add 1 to it and write it back to firebase; but the code I have currently seems to be a never ending loop

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)
}

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码-

ref.child("Vidpost").child(videoKey).child("video").child(userKey).child("like").child("count").setValue(like).updateChildValues(["count": like])

每次使用setvalue()时,都会替换以前的值。