我试图更新Firebase数据库,但遇到了这个问题。看看下面的代码片段和屏幕截图:
func saveRetrieveStoryID(completion: @escaping (Bool) -> Void) {
let userID = Auth.auth().currentUser?.uid
//Create a reference to the database
let DBRef = Database.database().reference()
let storyIDRef = DBRef.child("Story IDs").child(userID!)
storyIDRef.observe(.value) { (snapshot) in
for childOne in snapshot.children {
print(childOne)
if let childOneSnapshot = childOne as? DataSnapshot {
storyIDKeyList.append(Int(childOneSnapshot.key)!)
print(childOneSnapshot.key)
completion(true)
}
}
print(storyIDKeyList)
}
}
代码的作用是从数据库中检索密钥(-1)并将其存储在列表(storyIDKeyList)中。现在看看以下代码片段:
saveRetrieveStoryID { (saved) in
if saved {
// Store the story ID in the user's story ID dict
let storyIDRef = DBRef.child("Story IDs").child(userID!)
let newStoryIDKey = storyIDKeyList.last! + 1
storyIDs[String(newStoryIDKey)] = storyRef.key
storyIDRef.updateChildValues(storyIDs, withCompletionBlock: { (error, ref) in
if let error = error?.localizedDescription {
print("Failed to update databse with error: ", error)
}
})
}
}
这段代码,从storyIDKeyList中获取最后一项,并将其加1。然后,将其添加到storyIDs字典storyIDs[String(newStoryIDKey)] = storyRef.key
中,并使用新的键和值更新数据库。但是问题是,数据库一直在更新,直到我停止运行代码后数据库才会停止。这是生成的数据库的图片:
请注意,所有值都相同。以下屏幕截图应该是预期的结果:
我只想在每次运行代码时向数据库添加一个键/值;我有点知道为什么会这样,但我发现很难解决这个问题。
答案 0 :(得分:1)
经过大量尝试,我设法找到了解决此问题的方法。
编辑:由于此答案Android Firebase Database keeps updating value,我找到了一个更好的解决方案。使用observeSingleEvent()只检索一次数据。
以下是代码(更好地回答IMO):
func saveRetrieveStoryID(completion: @escaping (Bool) -> Void) {
let userID = Auth.auth().currentUser?.uid
let storyIDRef = DBRef.child("Story IDs").child(userID!)
storyIDRef.observeSingleEvent(of: .value) { (snapshot) in
for childOne in snapshot.children {
if let childOneSnapshot = childOne as? DataSnapshot {
storyIDKeyList.append(Int(childOneSnapshot.key)!)
}
}
completion(true)
}
}
旧答案(也适用):
func saveRetrieveStoryID(completion: @escaping (Bool) -> Void) {
let userID = Auth.auth().currentUser?.uid
let storyIDRef = DBRef.child("Story IDs").child(userID!)
storyIDRef.observe(.value) { (snapshot) in
for childOne in snapshot.children {
if let childOneSnapshot = childOne as? DataSnapshot {
storyIDKeyList.append(Int(childOneSnapshot.key)!)
}
}
storyIDRef.removeAllObservers()
completion(true)
}
}