Frederic
Frederic

Reputation: 497

Retrieving data from Firebase in Swift

I've been looking at the APIs from the Firebase website, however, 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() {
        super.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")


        usersRef.setValue([test_person_1])


        print(snapshot) //


    })

Json tree: enter image description here

Upvotes: 0

Views: 1561

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598603

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)")
    }
}

Upvotes: 1

Related Questions