What does the snapshot/observer code do in firebase?

后端 未结 2 1221
灰色年华
灰色年华 2021-01-27 07:19

When retrieving data from Firebase, we typically use the code below (or some reiteration of it)

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

var tempPo         


        
相关标签:
2条回答
  • 2021-01-27 08:09

    The code in your question uses .observeSingleEvent. What that means is that it's requesting data from Firebase immediately one time and will not observe any future changes or fire any other events.

    The data is returned in in the closure as a 'snapshot' and is a 'picture' of what that data looks like at a point in time. (snapshot...picture? Pretty snappy huh)

    Firebase data is only valid within the closure; any code following the closure will execute before Firebase has time to retrieve data from the server, so ensure you work with Firebase data inside that closure.

    The for loop iterates over the child nodes within the snaphot one at a time. For example, the snapshot could contain child snapshots of each user in a /users node. You can then get the users data from each child snapshot.

    The return statement should never be used within a asynchronous closure as you cannot return data (in that fashion) from a closure, so that line should be removed. You could however leverage an completion handler like this

    func getUser(with userID: String, completion: @escaping ((_ user: UserClass) -> Void)) {
    
      //get the user info from the snapshot, create a user object and pass it back
      //   via the completion
      completion(user)
    }
    

    to work with the data outside the closure.

    0 讨论(0)
  • 2021-01-27 08:19

    This code is used for observing data change in your database. You don't need to send requests from time to time for getting the latest data.

    When the data changes, it will trigger the closure you given so that you can do things. For more reference, you could read this doc.

    You could try this to covert snapshot into dictionary:

    for child in snapshot.children {
        let dataS = child as! DataSnapshot
        let dict = dataS.value as? [String : AnyObject]
        // handle the data
    }
    
    
    0 讨论(0)
提交回复
热议问题