【问题标题】:Updating Existing Object in Firebase with Swift 3使用 Swift 3 更新 Firebase 中的现有对象
【发布时间】:2017-04-14 19:25:51
【问题描述】:

我在保存从 Firebase 中提取的对象时遇到了问题。我想获取“cardAmount”的值,添加并保存。但它一直给我带来麻烦,因为它不能将数字转换为字符串。我想我可能会因为修改数据结构错误而挂断,但我已经坚持了一段时间 - 谁能给我一些指导,告诉我如何根据需要在 Firebase 中编辑单个子快照?

let sevenDayOption = UIAlertAction(title: "Seven Day: $31", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        let query = ref.queryOrdered(byChild: (FIRAuth.auth()!.currentUser?.uid)!)
        query.observeSingleEvent(of: .value, with: { (snapshot) in
            let cardAmount = snapshot.childSnapshot(forPath: "cardAmount").value as! Float
            let newAmount = cardAmount + 31
            let newAmountString = String(format:"%.2f", newAmount)
            snapshot.setValue(newAmountString, forKeyPath: snapshot.childSnapshot(forPath: "cardAmount").value as! String)
            print(snapshot.childSnapshot(forPath: "cardAmount").value as! Float) /*<---- Prints Optional(30.5)*/

        })
    })

我敢肯定,这可能很简单,但目前我也无法理解。对 Firebase 和 Swift 来说相对较新,所以有时与它搏斗有点挑战。

谢谢!

【问题讨论】:

  • runTransactionBlock。或者你可以使用 updateChildValues 方法
  • updateChildValues 完美运行!提交答案。非常感谢!

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

对于那些遇到此问题并在未来遇到麻烦的人 - 答案来自 Firebase 提供的 updateChildValues 方法:

let sevenDayOption = UIAlertAction(title: "Seven Day: $31", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        let query = ref.queryOrdered(byChild: (FIRAuth.auth()!.currentUser?.uid)!)
        query.observeSingleEvent(of: .value, with: { (snapshot) in
            let cardAmount = snapshot.childSnapshot(forPath: "cardAmount").value as! Float
            let newAmount = cardAmount + 31
            let newAmountString = String(format:"%.2f", newAmount)
            ref.updateChildValues(["cardAmount":newAmountString])/*<------ CRITICAL*/
        })
    })

非常感谢!

【讨论】:

    【解决方案2】:

    试试这个代码

    ref.child("yourKey").child("yourKey").updateChildValues(["cardAmount": yourNewCardAmount])
    

    这对我有用。希望能帮助别人...

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多