简体   繁体   中英

Swift retrieve data from Firebase

I've have tried different attempts of retrieving data from firebase (Database), but sadly with no luck :I... So I was wondering If this is the correct way of doing it?

let dBRef = Database.database().reference()
         dBRef.child("Users").child("Advertisements").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in

    let snapshotValue = snapshot.value as? NSDictionary

        let imageAd = snapshotValue?["imageAd"] as? String
        let priceAd = snapshotValue?["priceAd"] as? String

Im not sure if I actually receive the data, and Im not sure of how to test this as well... I have tried debugging but with no luck... So my question is, is my code wrongly done? and if not how do I check If I actually receive the data??

在此处输入图片说明

You are observing the childAdded event.

So your closure will only be executed when a new value I inserted into Users/Advertisements .

Try this code instead

Database
    .database()
    .reference()
    .child("Users")
    .child(Auth.auth().currentUser!.uid)
    .child("Advertisements")
    .queryOrderedByKey()
    .observeSingleEvent(of: .value, with: { snapshot in

        guard let dict = snapshot.value as? [String:Any] else {
            print("Error")
            return
        }
        let imageAd = dict["imageAd"] as? String
        let priceAd = dict["priceAd"] as? String
    })

The closure will be executed only once and "almost" immediately.

to test if your data was pulled in accurately, you can add, below your code: print(imageAd) . assuming this code is in viewDidLoad then it will show up in the console when the view controller comes up.

also, I believe .queryOrderedByKey(...) is now .queryOrdered(byKey:...)

keep in mind that .observe() essentially opens a connection to your firebase. if you want a live, realtime connection to stay open and listen for updates to data, this makes sense. if you only need the data once, when you load something, consider using .observeSingleEventOf() instead. if you are going to use .observe() , you should also use .removeAllObservers() to close the connection when you need it to be closed.

it seems like you are just trying to add this info which you've previously set up in your DB. I would do it like this - (keep in mind you were missing the uid step in your json. I have assumed it is the current user in the code below, but if it's a static user, you'd need to define it as a string):

let uid = Auth.auth().currentUser?.uid 
dBRef.child(Users).child(uid).child(Advertisements).observeSingleEvent(of: 
   .value, with: { (snapshot) in

  let value = snapshot.value as? NSDictionary
  let imageAd = value?["imageAd"] as? String ?? ""
  let priceAd = value?["priceAd"] as? String ?? ""

  print("imageAd: \(imageAd!)")
  print("priceAd: \priceAd!)")`
  })

I can see one problem is that your path is wrong. Try something like:

let dBRef = Database.database().reference()    
dBRef.child("Users/\(FirAuth.auth.currentUser.uid)/advertisements")

dbRef.queryOrderedByKey().observe(.childAdded, with: { (snapshot) in

I was having the same problem as yours but by looking at the firebase Doc you can see how to retrieve data easily.

lazy var databaseRef = Database.database().reference().child(yourpath).("Advertisements")

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

            let postDict = snapshot.value as? [String : AnyObject] ?? [:]

            if let email = postDict["Email"] {
                print(email)

            }



        }) { (error) in
            print(error.localizedDescription)
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM