【问题标题】:When I try to save data to Firebase it only updates the existing data, Swift, Firebase当我尝试将数据保存到 Firebase 时,它​​只会更新现有数据、Swift、Firebase
【发布时间】:2016-07-10 01:09:15
【问题描述】:

我设置数据库结构的方式是这样的:

它以 Lists 开头,然后有一个显示用户 UID 的子项,然后在里面有一个项目。

每次我尝试保存新数据时,UID 中的一项都会更新。而不是添加另一个项目,相同的项目只是不断变化。我想知道如何在每次添加更多项目时更新同一个项目。

我保存数据的方式就是使用这行代码。

let user = FIRAuth.auth()?.currentUser
let item: String = self.ItemTextField.text!
self.ref.child("Lists").child(user!.uid).setValue(["Items": item])

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    更惯用的方式是使用所谓的推送 id 存储项目列表:

    Lists
      twEymn...
        -Km....: "Yoghurt"
    

    你会这样做:

    self.ref.child("Lists").child(user!.uid).childByAutoId().setValue(item)
    

    childByAutoId() 生成一个唯一的、连续的 ID。它类似于数组索引,但它在多用户环境和用户可以离线时可靠地工作。阅读此blog post about these so-called push ids

    或者,您可以使用项目的名称作为键(如果项目在列表中必须是唯一的):

    Lists
      twEymn...
        "Yoghurt": true
    

    在这种情况下,代码变为:

    self.ref.child("Lists").child(user!.uid).child(item).setValue(true)
    

    您会注意到,这两种方法都只处理新添加的项目,而不是整个项目列表。这是您在使用 Firebase 时会看到的一般模式。通过隔离您的修改,您的应用将更具可扩展性,而无需用户互相干扰。

    【讨论】:

      【解决方案2】:

      问题在于您正在设置一个键值对(“Items”:item),以便每次更新相同键的值。你可以做的是 ("Items" : [your array of items here]),它每次都会更新相同键的项目列表。

      您还可以获取当前项目列表,在本地附加新项目,然后进行更新。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-08
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多