【问题标题】:How can I store multiple instances of different data with the same keyword in Firebase using Swift?如何使用 Swift 在 Firebase 中使用相同的关键字存储不同数据的多个实例?
【发布时间】:2020-06-05 05:08:10
【问题描述】:

我正在创建一个具有购物车系统的 iOS 应用。我有一个用于选择项目的屏幕,然后一旦单击该项目,它就会进入一个用于选择数量的新屏幕。将商品添加到购物车后,我想将其存储在 Firebase 中,以便当用户进入购物车时,可以从 Firebase 加载数据。我尝试了以下方法:

@IBAction func addToCartButtonPressed(_ sender: UIButton) {
    let reference = Database.database().reference.child("UserCart").child(Auth.auth().currentUser.uid)
    reference.updateChildValues(["Item Name": itemName, "Item Price": itemPrice, "Item Quantity": itemQuantity])
    self.dismiss(animated: true, completion: nil)
}

当我这样做时,我没有达到我想要的效果,因为如果用户从 Order View Controller 添加另一个项目,那么我刚刚写入 Firebase 的现有信息就会被覆盖。我知道这就是它的设计工作方式,所以我想知道是否有另一种方式可以写入 Firebase,并在 Firebase 中拥有多个 itemNameitemPriceitemQuantity 实例。我稍后计划读取这些数据并将其存储在一个数组中。如果有帮助,我正在使用 Swift 5。谢谢!

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    您需要阅读working with lists of data 上的文档。

    要写一个新项目,要做的事情是append to a list of data 使用childByAutoId()

    let reference = Database.database().reference
        .child("UserCart")
        .child(Auth.auth().currentUser.uid)
        .childByAutoId()
    

    SDK 会生成一个唯一的 ID,用作写入子节点的路径。由于对childByAutoId() 的每次调用都会生成一个唯一的 ID,因此每个新的孩子都将被单独添加,并且不会覆盖任何内容。

    【讨论】:

    • 您能否也编辑您的答案以涵盖我如何将这些放入数组中。我应该在第一次明确这一点,但我编辑了我的问题以涵盖我还需要什么。
    • 请单独询问psot后续问题。预计该问题显示了解决问题的尝试。 Stack Overflow 仅限于每个帖子一个问题/问题,以便人们轻松搜索和导航。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2016-01-10
    • 2014-05-15
    • 2020-08-12
    相关资源
    最近更新 更多