Salman Ali
Salman Ali

Reputation: 255

Firebase snapshot returns null

Hi guys I have been using firebase to write and read values from the database. It was working awesome until I wrote a function to retrieve values or products stored using swift in the following way.

Here is my code

func retrieveLiveUrlFor(product: Product){
    if let path = product.prodRef{
        print("Looking for : \(path)")
        var liveUrl = ""
        let ref = Database.database().reference(withPath: path)
        ref.observe(. value, with: {
            snapshot in
            print("Snap : \(snapshot.value)")
            if snapshot.exists(){
                print("Snap : \(snapshot.value)")
                let dic = snapshot.value as? NSDictionary
                if dic != nil{
                    let url = dic?["liveUrl"] as? String
                    print("Url is here")
                    if url != nil{
                        print("URL is not nil")
                        liveUrl = url as! String
                    }
                }
            }

            if (self.productdelegate != nil){
                print("Calling Product delegate")
                self.productdelegate?.liveUrlObtained!(liveUrl: liveUrl)
            }
        })
    }
}

And this is the value of the path that I am trying to retrieve

Products/Live/Global/WpMvDJZUclRlfHFJsSlBEbi0jHf1

And here is the snap of the firebase database

enter image description here

The snapshot.value alwasy returns null in swift. When I print using

print("Snap: \(snapshot.value)")

It prints the following

Snap : Optional() Please guide me what I am doing wrong so that I can get to it.

Upvotes: 0

Views: 5618

Answers (1)

Abishek Gokal
Abishek Gokal

Reputation: 186

If you are observing using the .value event, then a return of snapshot.value as nil means that the snapshot value does not exist at that reference. Try printing the snapshot as a whole and the snapshot.key

ideally the reference you need is

  let ref = Database.database.reference().child("Products").child("Live").child("Global").child("WpMvDJZUclRlfHFJsSlBEbi0jHf1")

The observer would function like this:

ref.observe(.value) {(snapshot) in
print(snapshot.value!)
}

Upvotes: 4

Related Questions