Frederic Frederic - 1 year ago 83
Swift Question

retrieving data from firebase in swift

I've been looking at the API's from the firebase website, however I when I print my snapshot I get EVERYTHING from my database.

I'm trying to only print the value I just set, which is my variable: "test_person_1:

import UIKit
import Firebase

class Test: UIViewController {

override func viewDidLoad() {

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

ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in

var test_person_1 = ["full_name": "Test 1", "date_of_birth": "June 1, 2000"]
var Test_person_2 = ["full_name": "Grace Hopper", "date_of_birth": "July 1, 2000"]
let usersRef = ref.child("New child")


print(snapshot) //


Json tree: enter image description here

Answer Source

By the time you print the snapshot, the value hasn't been set on the server yet.

If you want to print when the data been sent to the server, add a so-called completion listener to your setValue() call:

usersRef.setValue([test_person_1]) { (error, ref) in
    print(error, ref)

If there is no error, you know that the value on the server is what you just wrote. But if you want to read back the value from the server, you'll need to attach a listener for it:

usersRef.setValue([test_person_1]) { (error, ref) in
    ref.observeSingleEventOfType(.Value) { (snapshot) in
        print ("new value \(snapshot.value)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download