ios - 将 child 添加到 firebase (iOS) - 新 child 的插入不会停止

标签 ios swift firebase firebase-realtime-database

目前我正在创建一个应用程序,用户可以在其中创建和加入事件。我正在为如何跟踪用户加入的事件而苦恼。我决定为 Firebase 中的每个用户存储一组“事件键”(事件 ID)。但是,当用户点击“加入事件”按钮时,Firebase 会向用户添加数百个新子项(具有相同的事件键)。它看起来像某种无限循环(但我没有使用任何循环)。首先,我从 Firebase 加载当前事件键数组,然后将新事件键附加到该数组。然后,必须更新 eventKeys 子项。

@IBAction func joinEventButtonTapped(_ sender: UIButton) {

    guard let uid = user?.uid else {
        return
    }

    let ref = Database.database().reference(withPath: "users").child(uid)

    ref.observe(.value) { (snapshot) in
        self.currentUser = CustomUser(snapshot: snapshot)

        if let currentUserEventKeys = self.currentUser?.eventKeys, let newEventKey = self.currentEvent?.key {
            var eventKeys: [String] = currentUserEventKeys
            eventKeys.append(newEventKey)
            let values = ["eventKeys": eventKeys]
            ref.updateChildValues(values)
        }
    }
}

var currentUser: CustomUser?
var currentEvent: CustomEvent?
let user = Auth.auth().currentUser

我的代码有什么问题?

最佳答案

在调用 ref.observe 的地方,这是一个开放式观察,一旦调用,将永远观察数据库中的该路径,并在更新值时执行其中的代码。当您更新其中的代码(更新一个值)时,这也会触发 ref.observe(一直在寻找更新值的开放观察),这意味着它也会触发内部代码,再次更新它,创建无限循环。您需要改用 Firebases observeSingleEvent

关于ios - 将 child 添加到 firebase (iOS) - 新 child 的插入不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412540/

相关文章:

ios - NSString 到 byte Array,操作它,以及 byte Array 到 NSString

ios - 在 UIViewController Extension 中引用全局字符串变量

ios - 如何使用 UISegmentedControl 更改 Swift 中的标签?

ios - 如何通过 GeoFire 正确使用存储的搜索半径?

javascript - 如何检查 Firestore 查询是否为空或我尝试获取的文档不存在?

ios - Firebase signInWithCredential 使用 Facebook SDK 给出错误

ios - 在 View Controller 之间移动数据,并在 Swift 的 Web View 中显示移动的数据

ios - 获取tableview的可见矩形

swift - 当您在锁定屏幕 Xcode 6 中时应用程序正在运行

ios - 动态链接对象没有 url