Swift 3的异步功能和Firebase [英] Asynchronous functions and Firebase with Swift 3
问题描述
我读了一些有关此的问题.但是我仍然对异步功能有疑问.
I read some questions about that. But I still have issues with asynchronous functions.
例如:我有一个 viewController1
,其中一个按钮对 viewController2
执行了搜索.在 viewController2
类中,我在另一个名为 exampleClass
的类文件中初始化一些值.这些值是从Firebase数据库或位置值中检索的.这些值需要一点时间来检索.我将这些值从 exampleClass
返回到我的 viewController2
中.我在 viewController2
viewDidLoad()
中打印这些值.
For example: I have a viewController1
where a button perform a segue to a viewController2
. In the viewController2
class, I initialize some values in another class file named exampleClass
. These values are retrieved from Firebase database or location values. These values need a little moment to be retrieved. I return thes values from the exampleClass
into my viewController2
. I print these values in the viewController2
viewDidLoad()
.
我的问题:设备不等待取回值并执行以下功能.结果:当我触摸按钮时,打印的值是 nil
值.如果我不保护代码,它也会使应用程序崩溃.
My issue: The device doesn't wait that the values are retrieved and execute following functions. Result: When I touch the button, printed values are nil
values. It can also make the app crash if I don't secure the code.
到目前为止,我发现的信息:我了解到,我只需要在Firebase snapshot
(例如)的末尾调用一个func,如下所示:
What I've found so far: I learned that I only have to call a func at the end of a Firebase snapshot
(for example) like this:
userRef.observeSingleEvent(of: .value, with: { (snapshot) -> Void in
self.name = snapshot.value as! String!
print(self.name)
self.forceEnd()
}) { (error) in
print(error.localizedDescription)
}
我将此函数命名为 forceEnd
以使其清晰.这对我不起作用.我也尝试创建处理程序,但没有任何积极结果.
I named this function forceEnd
to be clear. This is not working for me. I also tried to create handlers but no positive results.
我的问题:在执行以下问题之前,如何强制设备等待检索值?
My question: How can I force the device to wait for the values to be retrieved before performing the following question?
推荐答案
在执行以下问题之前,如何强制设备等待取回值?
How can I force the device to wait for the values to be retrieved before performing the following question?
- 您不想强制等待设备,只需要在从Firebase数据库中检索到这些值后执行一些操作即可.
- 可以以多种方式异步执行操作,例如协议,通知等
- You don't want to force the device to wait, only need to perform some operations once these values are retrieved from Firebase database.
- Performing an operation asynchronously can be done in multiple ways like blocks, protocols, notifications, etc.
通常,积木是更优雅的方法.
一些示例代码可能类似于:
Generally, blocks are the more elegant approach.
Some sample code can be like:
func myFirebaseNetworkDataRequest(finished: () -> Void) { // the function thats going to take a little moment
...
print("Doing something!") // firebase network request
finished()
}
// usage of above function can be as-
override func viewDidLoad() {
myFirebaseNetworkDataRequest {
// perform further operations here after data is fetched
print("Finally! It took a lot of moments to end but now I can do something else.")
}
}
这篇关于Swift 3的异步功能和Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!