当帖子获得超过2个标志时,我一直在尝试从firebase中删除帖子。我尝试了很多方法,但我无法弄明白。我有一些图片附加帮助将不胜感激! `
// 4
if poster.uid != User.current.uid {
let flagAction = UIAlertAction(title: "Report as Inappropriate", style: .default) { _ in
PostService.flag(post)
/// addedflag
let flaggedPostRef = Database.database().reference().child("flaggedPosts").child(postKey!)
// 3
var flaggedDict = ["text": post.textData,
"poster_uid": post.poster.uid,
"reporter_uid": User.current.uid]
// 4
flaggedPostRef.updateChildValues(flaggedDict)
// 5
let flagCountRef = flaggedPostRef.child("flag_count")
flagCountRef.runTransactionBlock({ (mutableData) -> TransactionResult in
let currentCount = mutableData.value as? Int ?? 0
mutableData.value = currentCount
if mutableData.value as! Int >= 1 {
let uid = FIRAuth.auth()!.poster.uid!.uid
// Remove the post from the DB
ref.child("posts").child(postKey).removeValue { error in
if error != nil {
print("error \(error)")
}
}
postKey?.removeVolue()
let timelinePostDict = ["poster_uid" : poster.uid]
var updatedData: [String : Any] = ["timeline/\(poster.uid)/\(postKey)" : timelinePostDict]
let postToBeDeleted = Database.database().reference().child("posts")
updatedData["timeline/\(poster.uid)/\(postKey)"] = timelinePostDict
updatedData["posts/\(poster.uid)/\(postKey)"] = postKey
print("Delete case: mutableData.value = \(mutableData.value)")
} else {
print("Case not met. Either not equal to 2 or not able to cast as Integer type. The value of the casted in is \(mutableData.value as? Int)")
}
mutableData.value = currentCount + 1
return TransactionResult.success(withValue: mutableData)
})
答案 0 :(得分:0)
在特定节点上追加/更新值之前,.runTransactionBlock({..
会多次触发。你需要的是观察者: -
Database.database().reference().child("flaggedPosts").observe(.childChanged, with: {(Snapshot) in
// Every time a child dictionary in the flaggedPosts node
// would change you will receive that dictionary in this block
// be it any change in any of the values in that postKey
// Check the flagCount value and perform the action requisite...
print(Snapshot.value ?? "No value retrieved")
if let snapDict = Snapshot.value as? NSDictionary{
let count = snapDict["count"] as! Int
let postID = snapDict["postKey"] as! String
let posterUID = snapDict["poster_uid"] as! String
if count > 1{
print(postID)
// You will only be pushed into this block only if your count value
// is greater than 1 i.e 2
// Delete postID in your database
Database.database().reference().child("posts/\(posterUID)/\(postID)").removeValue(completionBlock: {(Err, ref) in
// Handle the error you recieve while deleting
// the flagged post
})
}
}
}, withCancel: {(Error) in
// Handle the error recieved while making
// a call to firebase
})
鉴于此方法使用.observe(.childChanged..
,这是一个异步活动调用,其观察者不会从网络链接中删除。到您的数据库,每次更换/更新您的孩子时都会触发...
答案 1 :(得分:0)
let flaggedPostRef = Database.database().reference().child("flaggedPosts").child(postKey!)
我修好了 - 我找到了一种找到海报uid和post键的方法,只是删除了值。