Wp3Dev
Wp3Dev

Reputation: 2079

Reading Data stored via Autoid from Firebase Swift

I am trying to access the contents of data that is stored via childByAutoID in firebase using swift. Currently I am very new to this and am just printing out the value of snapshot.value. I want to be able to access both key value pairs stored in each ID.

Here is my current code:

override func viewDidLoad() {
        super.viewDidLoad()

        let ref = FIRDatabase.database().reference()

        ref.child("Phrases").observeSingleEvent(of: .value, with: {
            snapshot in

            let value = snapshot.value as? NSDictionary

            print(value)

        })



    }

This is outputting:

Optional({
    "-KkNM7b33sqba0XF-Nob" =     {
        phrase = "Bonjour!";
        translation = "Hello!";
    };
})

I am want to be able to access value["phrase"] and translation as well.

How do I do this?

EDIT: Here is a photo of the db:enter image description here

Upvotes: 1

Views: 614

Answers (1)

Chris
Chris

Reputation: 8020

The way I usually do this is by:

ref.child("Phrases").observeSingleEvent(of: .value, with: { snapshot in

 let value = snapshot.value as! [String:Any]
 let name = value["phrase"] as? String ?? ""
})

Alternatively you could unwrap it first

ref.child("Phrases").observeSingleEvent(of: .value, with: { snapshot in

  if let value = snapshot.value as? [String:Any] {
    let name = value["phrase"] as? String ?? ""
  }
})

Upvotes: 2

Related Questions