What does the snapshot/observer code do in firebase?

后端 未结 2 1228
灰色年华
灰色年华 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.

提交回复
热议问题