0

I've been having trouble saving an object pulled in from Firebase. I want to grab the value of 'cardAmount', add to it and save it. But it keeps giving me trouble about it not being ale to convert a number to a string. I think I might be hung up on modifying the data structure wrong, but I've been stuck on this for a little while - can anyone give me some guidance on how to edit a single Child Snapshot in Firebase as I need it?

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)*/

        })
    })

I'm sure it's probably something simple, but it's also something that eludes me at the moment. Relatively new to Firebase and Swift so its been a bit of a challenge wrestling with it at times.

Thanks!

2
  • 1
    there is runTransactionBlock. Or you can use updateChildValues method Commented Nov 30, 2016 at 12:58
  • updateChildValues worked perfectly! Submitting answer. Thank you so much! Commented Nov 30, 2016 at 13:16

2 Answers 2

1

For those of you who come across this and have trouble in the future - the answer came from the updateChildValues method that Firebase offers:

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*/
        })
    })

Thank you so much!

Sign up to request clarification or add additional context in comments.

Comments

0

Try this code

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

This worked for me. Hope will help someone...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.