【发布时间】:2019-08-29 15:59:57
【问题描述】:
我在尝试更新我的 Firebase 数据库时遇到了这个问题。看看下面的代码sn-p和截图:
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) 中。现在看看下面的代码sn-p:
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 中,并且数据库将使用新的键和值进行更新。但问题是,数据库不断更新,直到我停止运行代码才停止。这是生成的数据库的图片:
请注意,所有值都是相同的。以下屏幕截图应该是预期的结果:
我只想在每次运行代码时向数据库添加一个键/值;我有点知道为什么会这样,但我发现很难解决这个问题。
【问题讨论】:
标签: swift firebase firebase-realtime-database