[英]Firebase iOS - Snapshot suddenly returning null when I know a value exists
[英]Firebase ios snapshot returning null for .childRemoved
我刚刚开始在Swift中使用Firebase,并有一个示例消息节点。 我添加了包含文本和用户名等的消息子级。我将安全规则设置为对每个.write和.read进行身份验证。 我创建了一个观察器来监视该事件,并且它正在触发,但是返回的快照为null。 我需要快照数据的原因是,我可以从客户端删除该确切消息。
数据节点结构:
{
"messages" : {
"-KcM3SlAQXfjCz01waXF" : {
"name" : "mgardner1994",
"text" : "test23"
},
"-KcM3UKA_U7n2YwhlFeB" : {
"name" : "mgardner1994",
"text" : "test4"
},
"-KcMB_8Ec74HIQGL9adt" : {
"name" : "mitchell_maler",
"text" : "test5"
},
"-KcOC08kLUO-cEWLeICG" : {
"name" : "mitchell_maler",
"text" : "hello"
},
"-KcOC6ZWT6gyVi6pxGF8" : {
"name" : "mitchell_maler",
"text" : "test"
}
}
}
规则:
{
"rules": {
"messages": {
".read": "auth != null",
".write": "auth != null"
}
}
}
SWIFT代码:
_refHandleDel = ref.child("messages").observe(.childRemoved, with: { (snapshot) -> Void in
// TODO: Why is snapshot returning nil
let index = self.messages.index(of: snapshot)
self.messages.remove(at: index!)
self.messagesTable.deleteRows(at: [IndexPath(row: index! , section: 0)], with: .automatic)
})
编辑:将数据结构添加到文本而不是图像。
通过创建用于查找密钥的查找功能,我能够解决该问题。 我仍然不确定为什么index(of)方法不起作用,但是会继续挖掘。
_refHandleDel = ref.child("messages").observe(.childRemoved) { (snapshot: FIRDataSnapshot!) in
print(snapshot)
// Never finds the object and returns nil
let index = self.messages.index(of: snapshot)
print(index ?? "no")
// using the workaround method it finds the index using the key
let index2 = self.indexOfSnapshotInArray(snapshot: snapshot, snapshotArray: self.messages)
print(index2)
if (index2 != -1) {
self.messages.remove(at: index2)
self.messagesTable.deleteRows(at: [IndexPath(row: index2 , section: 0)], with: .automatic)
} else {
print("Could not find message in array.")
}
}
func indexOfSnapshotInArray(snapshot: FIRDataSnapshot, snapshotArray: [FIRDataSnapshot]) -> Int {
var index = 0
for snap in snapshotArray {
if (snapshot.key == snap.key) {
return index
}
index += 1
}
return -1
}
您可能想以另一种方式进行处理:
每个快照(或子快照)将具有一个密钥,这就是您应该在数组(表,dataSource等)中查找的内容
换句话说,当消息最初加载时(例如,加载到dataSource中),它们将位于key:value对中
messages
-KcM3SlAQXfjCz01waXF (the key)
name : "mgardner1994", (the values which are a dictionary)
text : "test23"
理想情况下,您将获得这些键值对的数组
a[0] = key:value = -KcM3SlAQXfjCz01waXF: dictionary of children
a[1] = key:value = -KcM3UKA_U7n2YwhlFeB: dictionary of children
注意上面是字典,但是它可以是UserClass或ItemsClass
a[0] = aUser (UserClass)
a[1] = aUser (UserClass)
当您的应用收到删除事件时,会将键:值对作为快照传递。 我们不在乎值,但在乎键,因为您可以在数组中找到该项目的索引并将其删除。 (通过ObjC NSPredicate查找匹配项)或...例如,如果您使用的是UserClass,则在Swift中类似这样
func handleChildRemoved(_ snapshot: FDataSnapshot! ) {
let key = snapshot.key
if let index = self.usersArray.indexOf({$0.firebaseKey == key}) {
self.usersArray.removeAtIndex(index)
self.usersTableView.reloadData()
}
}
在这个例子中,我有UserClass
class UserClass {
firebaseKey = ""
userName = ""
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.