从Firebase

时间:2016-10-21 17:31:00

标签: swift firebase firebase-realtime-database swift3

我尝试删除属于特定用户的所有帖子,但是它崩溃告诉我错误:

  

' - [FIRDataSnapshot removeValue]:发送到的无法识别的选择器   实例0x174238c20'

但如果我尝试po孩子,它会打印出孩子。

这就是我在 Swift3

中的表现
FIRDatabase.database().reference().child("posts").queryEqual(toValue: self.currentUser.generalDetails.userName).ref.observe(.value, with: { (snapshot: FIRDataSnapshot!) in
            for child in snapshot.children {
                (child as AnyObject).removeValue() //This line gives the error.   
            }
        })

如果"username":"currentUser.generalDetails.userName"

,那就是要删除的孩子
posts
    -KUaMd3YgJlQvv_P-kdK//This has to be deletod with all its children
       content: 
       likes: 
       postId: 
       postImageStringUrl: close
       profileImageUrl: 
       timestamp: 
       username: 

什么应该导致崩溃?

编辑:我更新了这样的代码,说明我必须:

  

考虑在您的安全性中添加“.indexOn”:“posts / username”   提高绩效的规则

但是我的安全规则非常好:

{ 
"rules": { 
".read": "auth != null", 
".write": "auth != null", 
"Snuses": { 
".indexOn": ["Brand", "posts/username"]
} 
} 
}
FIRDatabase.database().reference().queryOrdered(byChild: "posts/username").queryEqual(toValue: currentUser.generalDetails.userName)
            .observeSingleEvent(of: .value, with: { snapshot in

                if ( snapshot.value is NSNull ) {
                    print("not found")
                } else {
                    for child in (snapshot.children) {
                        let element = child as! FIRDataSnapshot //the node data
                        let key = element.key //the key for the node
                        let nodeToRemove = FIRDatabase.database().reference().child(key)
                        nodeToRemove.removeValue()
                    }
                }
            })

2 个答案:

答案 0 :(得分:2)

我相信你会想要通过它的父键来移除孩子,而不是孩子。

弗兰克提供了一个简短的评论(这实际上是答案),但这里有一个冗长的例子(Firebase 2.x,但你会明白这一点):

ref.queryOrdered(byChild: "posts/username").queryEqual(toValue: "someUsername")
     .observeSingleEvent(of: .value, with: { snapshot in

     if ( snapshot?.value is NSNull ) {
           print("not found")
     } else {
           for child in (snapshot?.children)! {
                let element = child as! FDataSnapshot //the node data
                let key = element.key! //the key for the node
                let nodeToRemove = ref.child(byAppendingPath: key)
                nodeToRemove?.removeValue()
     }
  }
})

要寻找的是确保您的路径正确。

在上面的代码中,'key'是父节点名称,如

-KUaMd3YgJlQvv_P-kdK

如果您要使用

let ref = element.ref

它将是该节点的特定路径,包括节点名称,但没有其他数据,如此

root_node/posts/-KUaMd3YgJlQvv_P-kdK

所以我们的想法是,一旦你有了这个引用,请使用引用删除节点。

所以如果ref = root_node / posts / -KUaMd3YgJlQvv_P-kdK

然后ref.remove(),它将删除该引用和子数据。

答案 1 :(得分:1)

虽然@ Jay的答案可以解决你的问题,但我已经写完了你的答案了一半,试一试并让我知道: -

RewriteEngine On
 RewriteRule ^/$ views/home/index.php [L]

它应该删除用户发的每个帖子.. :)