Enes
Enes

Reputation: 79

Fetch Firebase child data in Swift

I already have setup Firebase on Xcode 9.

My question: I want to retrieve data from Firebase. This works but when I add another text in a group it wont retrieve.

Example

FIREBASE:

lang :

  "Deutsch"

  "Englisch"

Firebase Image Example because it's difficult to explain:

Firebase Image Example beacause it's difficult to explain

import UIKit
import FirebaseDatabase

class ViewController: UIViewController {

    @IBOutlet weak var outputone: UILabel!
    // @IBOutlet weak var outputtwo: UILabel!

    var dbReference: DatabaseReference?
    var dbHandle: DatabaseHandle?

    override func viewDidLoad() {
        super.viewDidLoad()

        dbReference = Database.database().reference()
        // dbReference?.child("lang").childByAutoId().setValue("Deutsch")
        // dbReference?.child("lang").childByAutoId().setValue("Englisch")

        // retrieve data
        dbHandle = dbReference?.child("lang").observe(.childAdded, with:{ (snapshot) in
            let lang:String? = snapshot.value as? String
            self.outputone.text = (lang)
        })

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

I want that "Deutsch" displays in outputone and "Englisch" in outputtwo

Can someone help ?

Upvotes: 2

Views: 868

Answers (2)

James Kim
James Kim

Reputation: 49

when retrieving the data from Firebase, it's come as a chunk. This is when the downCasting comes in handy.

dbHandle = dbReference?.child("lang").observe(.childAdded,  with:{(snapshot) in

    guard let dictionary = snapshot.value as? [String:Any],
    let de = dictionary["de"] as? String, 
    let en = dictionary["en"] as? String else {
    "error occurs when down casting.."
     return}

   self.outputone.text = de
   self.outputwo.text = en 
})

whenever dealing with a dictionary approach, it's dangerous to hardcode string key every time. it's error-prone. I recommend you create a struct holding each key so you don't need to type string every time needed.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598718

Right now you retrieve the entire lang node. So the snapshot you get from Firebase contains both "de": "Deutch" and "en": "English". When you now do snapshot.value as? String, it returns nil since the snapshot doesn't have a single, simple string value.

To get the specific values, you first need to tell the snapshot which child property you want: de or en, and then you can get the string value.

dbHandle = dbReference?.child("lang").observe(.value,  with:{(snapshot) in
    let de:String? = snapshot.childSnapshot(forPath:"de").value as? String
    let en:String? = snapshot.childSnapshot(forPath:"en").value as? String
    self.outputone.text = (de)
    self.outputtwo.text = (en)
})

Upvotes: 2

Related Questions