如何从firebase删除帖子?迅速

时间:2017-12-25 17:30:06

标签: swift firebase firebase-realtime-database

我一直在尝试很多东西,而且我一直在互联网上搜索很多,但由于我的代码设置方式,我无法找到帮助我的解决方案。

我是如何尝试删除帖子的,但我真的不知道如何执行此操作,因为我的帖子是在firebase生成的自动ID中上传的,我不知道该写什么

Database.database().reference.child("posts").child("HERE IS THE AUTO ID").removeValue

我如何得到这个?请帮助我,我现在已经被困在这个问题上了一段时间。 我不知道如何获得autoid。

这是我上传帖子的方式

   if (self.imageFileName != "") {
        if choosenCountryLabel.text == "Albania" {
            // image has finshed the uploading, Saving Post!!!
            if let uid = Auth.auth().currentUser?.uid {

                Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
                    if let userDictionary = snapshot.value as? [String: AnyObject] {
                        for user in userDictionary{
                            if let username = user.value as? String {
                                if let streetAdress = self.locationAdressTextField.text {
                                    if let title = self.titleTextField.text {
                                        if let content = self.contentTextView.text {
                                            let postObject: Dictionary<String, Any> = [
                                                "uid" : uid,
                                                "title" : title,
                                                "content" : content,
                                                "username" : username,
                                                "time" : self.timeStamps,
                                                "timeorder" : self.secondTimeStamps,
                                                "image" : self.imageFileName,
                                                "adress" : streetAdress,
                                                "postAutoID" : self.postAutoID
                                            ]


                                            let postID = Database.database().reference().child("posts").childByAutoId()
                                            let postID2 = Database.database().reference().child("AlbaniaPosts").childByAutoId()
                                            let postID3 = Database.database().reference().child(uid).childByAutoId()

                                            postID.setValue(postObject)
                                            postID2.setValue(postObject)
                                            postID3.setValue(postObject)
                                            let postAutoID = postID.key
                                            let postAutoID2 = postID2.key
                                            let postAutoID3 = postID3.key
                                            print(postAutoID)
                                            print(postAutoID2)
                                            print(postAutoID3)

                                            let alertPosting = UIAlertController(title: "Successfull upload", message: "Your acty was successfully uploaded.", preferredStyle: .alert)
                                            alertPosting.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
                                                let vc = self.storyboard?.instantiateViewController(withIdentifier: "AlbaniaVC")
                                                self.present(vc!, animated: true, completion: nil)
                                            }))
                                            self.present(alertPosting, animated: true, completion: nil)



                                            print("Posted Succesfully to Firebase, Saving Post!!!")

                                        }
                                    }
                                }
                            }
                        }
                    }
                })
            }

        }
    }else{
        let alertNotPosting = UIAlertController(title: "Seems like you got connection problems", message: "Your image has not been uploaded. Please Wait 10 seconds and try again.", preferredStyle: .alert)
        alertNotPosting.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alertNotPosting, animated: true, completion: nil)
    } 

and here is the query in firebase.

2 个答案:

答案 0 :(得分:0)

Delete data

  

删除数据的最简单方法是在引用上调用remove()   该数据的位置。

     

您也可以通过将null指定为另一个写入的值来删除   诸如set()或update()之类的操作。您可以使用此技术   update()在单个API调用中删除多个子节点。

答案 1 :(得分:0)

您在查询数据时必须保存autoID,或者在上传时必须将密钥保存在帖子中。

如果想在查询时获取密钥。你可以这样做:

let ref = Database.database().reference()
ref.child("posts").queryLimited(toLast: 7).observeSingleEvent(of: .value, with: { snap in
    for child in snap.children {
        let child = child as? DataSnapshot
        if let key = child?.key { // save this value in your post object
            if let post = child?.value as? [String: AnyObject] {
                if let adress = post["adress"] as? String, let title = post["title"] as? String { // add the rest of your data
                    // create an object and store in your data array
                }            
            }
        }
    }
})

请注意,上述查询仅获取最近7篇帖子。如果您想继续获得更多,您需要查看pagination

如果您想在帖子中保存ID,只需在上传时添加:

let key = ref.child("posts").childByAutoId().key

let post = ["adress": adress,
            "content": content,
            "postID": key] as [String: Any]

let postFeed = ["\(key)" : feed]

ref.child("posts").updateChildValues(postFeed, withCompletionBlock: { (error, success) in
    if error != nil {
        // report the error
    }
    else {
        // everything is fine
    }
})

然后当您查询时,您可以执行以下操作:

let ref = Database.database().reference()
ref.child("posts").observeSingleEvent(of: .value, with: { snap in
    for child in snap.children {
        if let post = child?.value as? [String: AnyObject] {
            if let postID = post["postID"] as? String {
                // save this key in a post object so you can access it later to delete
            }
        }
    }
})

现在假设您创建了一个名为post的对象,您可以使用

删除该帖子
ref.child("posts").child(post.postID).removeValue(completionBlock: { (error, refer) in
    if error != nil {
        // failed to delete post                    
    }
    else {
        // delete worked
    }
})