Victor Appercé
Victor Appercé

Reputation: 25

Retrieving Firebase Database value Swift Xcode

I have a lite problem, I cannot recover the carte value in my database. when i get there for username. But the path is good.

My code :

 override func viewDidLoad() {

        super.viewDidLoad()
        loadCarte()

}

func loadCarte(){
        var ref: DatabaseReference!

        ref = Database.database().reference()
        let userID = Auth.auth().currentUser?.uid
        ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
          // Get user value
          let value = snapshot.value as? NSDictionary
          let Carte = value?["carte"] as? String ?? ""
            self.carteButton.setTitle(Carte + " cartes", for: .normal)
          // ...
          }) { (error) in
            print(error.localizedDescription)
        }
    }

I manage to recover other values but not that one, can that come from the fact that its being an Integer?

Thank's in Advance

EDIT : my Json structure of a User Type under users > userID

    {
  "carte" : 10,
  "email" : "[email protected]",
  "username" : "vicro87000"
}

Upvotes: 0

Views: 65

Answers (2)

Jay
Jay

Reputation: 35657

Assuming you're structure is:

uid_0
  "carte" : 10,
  "email" : "[email protected]",
  "username" : "vicro87000"

And you want to read in the child values, here's some code to read that node

let thisUser = ref.child("users").child(uid)
thisUser.observeSingleEvent(of: .value, with: { snapshot in
    let email = snapshot.childSnapshot(forPath: "email").value as? String ?? "No email"
    let userName = snapshot.childSnapshot(forPath: "username").value as? String ?? "No username"
    let carte = snapshot.childSnapshot(forPath: "carte").value as? Int ?? 0
    print(email, username, carte)
})

So the carte var will be an Int and can be used in a label

myTextField.text = "\(carte)"

or cast to a String

let myIntAsString = String(carte)

this

as? Int ?? 0

is called a nil coalescing operator and protects your code in case the value is set to nil, it actually is set to 0 so you're code doesn't crash.

As a side note, this is dangerous

userID!

as force-unwrapping an optional can lead to a crash

Better to do

guard let user = Auth.auth().currentUser else {return}
let uid = user.uid

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 599041

You're storing a numeric value in the carte property, so you're casting a numeric value to a string. In Swift you can't cast a number to a string like that.

I've been told by a Swift expert that this is the best way to accomplish the same:

let carte = value?["carte"].flatMap { $0 as? Int } .map { String($0) }

The flatMap operation here unwraps the int value from inside the optional that it's in. Then the map converts the int value to a string. Calling the String initializer in the map closure is required because Swift Ints are not castable to String types.

Upvotes: 2

Related Questions