Updating child value in Firebase

I want to update a child value called "PhotoGallery" in a child called "users".

How do I rewrite this code to do so.

func registerDatabase(id: String, url: [String: AnyObject]) {

        //Create a database reference
        let userRef = self.databaseRef.child("users").childByAutoId().child(id)

        userRef.updateChildValues(["PhotoGallery":url]) {(error, ref) in

            if error != nil{
                print("Error registering Firebase database: \(error)")

                return
            }

            print("Successfully stored in DB")
        }
    }

    func removeSpecialCharsFromString(text: String) -> String {
        let validChars: Set<Character> = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters)

        return String(text.characters.filter{validChars.contains($0)})
    }

Upvotes: 0

Views: 1233

Answers (1)

Jay
Jay

Reputation: 35657

A setValue will do it since you are creating the child node on the fly with childByAutoId.

let userChildRef = self.databaseRef.child("users").childByAutoId()
let photoRef = userChildRef.child("id").child("PhotoGallery")
photoRef.setValue(url)

results in

users
   -Yuhusn9asijasd
      id
       PhotoGallery: "www.someurl.com"

note I left photoRef as a separate let to make it more readable since userChildRef now refers to all of the children of that user

let nameRef = userChildRef.child("name")
nameRef.setValue("Gilligan")

let hatColorRef = userChildRef.child("hat")
hatColorRef.setValue("White")

let shirtColorRef = userChildRef.child("shirt")
shirtColorRef.setValue("Red")


users
   -Yuhusn9asijasd
      id:
        PhotoGallery: "www.someurl.com"
      name: "Gilligan"
      hat: "White"
      shirt: "Red"

Upvotes: 1

Related Questions