Firebase数据库不会停止更新

Abd*_*mal 5 firebase swift firebase-realtime-database

我试图更新我的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)
    }
}
Run Code Online (Sandbox Code Playgroud)

Firebase数据库

该代码的作用是从数据库中检索密钥(-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)
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码从storyIDKeyList中获取最后一个项目,并将其加1。然后,将其添加到storyIDs词典,storyIDs[String(newStoryIDKey)] = storyRef.key并使用新的键和值更新数据库。但是问题是,数据库一直在更新,直到我停止运行代码后数据库才会停止。这是结果数据库的图片:

结果数据库

请注意,所有值都相同。以下屏幕截图应该是预期的结果:

预期结果

我只想在每次运行代码时向数据库添加一个键/值;我有点知道为什么会这样,但是我发现很难解决这个问题。

Abd*_*mal 1

经过多次尝试,我设法找到了解决这个问题的方法。

编辑:我找到了一个更好的解决方案,感谢这个答案:Android Firebase Database keep update 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

旧答案(也有效):

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)
    }
}
Run Code Online (Sandbox Code Playgroud)