快照/观察者代码在firebase中有什么作用? [英] What does the snapshot/observer code do in firebase?

查看:35
本文介绍了快照/观察者代码在firebase中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Firebase检索数据时,我们通常使用下面的代码(或重复一些代码)

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

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

var tempPosts = [PostModel]()

for child in snapshot.chidren{
}

return tempPosts

})

但是我不完全了解这段代码在做什么吗?有人可以高水平解释吗?我曾尝试在多个斑点上打印数据,但我获得的唯一数据是:Snap post或[App.PostModel]

but I don't exactly get what this code is doing? Can someone explain it on a high level? I've tried printing data on mulitple spots but the only data I'm getting is: Snap post or [App.PostModel]

推荐答案

问题中的代码使用.observeSingleEvent.这意味着它一次会立即从Firebase请求数据,并且不会观察到任何将来的更改或触发任何其他事件.

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数据仅在闭包内有效;关闭后的所有代码都将在Firebase有时间从服务器检索数据之前执行,因此请确保在该关闭内 内使用Firebase数据.

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.

for循环一次遍历快照中的一个子节点.例如,快照可以包含/users节点中每个用户的子快照.然后,您可以从每个子快照中获取用户数据.

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.

决不能在异步闭包中使用return语句,因为您不能从闭包中返回数据(以这种方式),因此应删除该行.但是,您可以利用这样的完成处理程序

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

使用闭包外部的数据.

这篇关于快照/观察者代码在firebase中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆