当Firebase功能在Swift中结束时 [英] When Firebase function ends in Swift
问题描述
我在我的应用程序中使用Firebase,它查询大量用户并获取所需的特定数据,但是当它开始查询时-该功能的其余部分也保持运行,而不仅仅是查询,因此我可以不知道什么时候结束.
I am using a Firebase in my app, it queries through a lot of users and gets the specific data that is needed, but when it starts querying - the rest of the function keep running too, instead of just querying so I can't understand when it ends.
例如下面的代码:
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
let user = snapshot.value!.objectForKey("User")
let name = (user!["Name"])! as! String
print("name")
})
print("done")
假设我们在Firebase数据库中有3个用户-打印的代码将是:
Let's say we have 3 users in the Firebase Database - the printed code will be:
done
nameuser1
nameuser2
nameuser3
(或done
将在名称用户之间,取决于您的Internet连接-但不会是最后一个)
(or the done
will be somewhere between the nameusers, depends on your internet connection - BUT it won't be the the last)
推荐答案
您遇到的问题"是由于函数observeEventType()
是异步的.因此,它会在实际获取值之前将控制权返回给其调用方.使用这样的异步回调并传递一个函数,该函数每次在从firebase中检索值时都会被调用...
The "problem" your experiencing is due to the function observeEventType()
being asynchronous. So it returns control to its caller before the values have actually been retrieved. Use an asynchronous callback like this and pass a function that will be called each time a value is retrieved from firebase...
已为Swift 3更新
func getDataFromFirebase(callback: @escaping (_ user: String, _ name: String)->Void){
ref.observeEvent(of: .childAdded, with:{(snapshot)-> Void in
let user = snapshot.value!.objectForKey("User") as! String
let name = (user!["Name"])! as! String
callback(user, name)
})
}
并像这样调用函数...
and call the function like this...
getDataFromFirebase(callback: {(user, name)-> Void in
print("got a user: \(user) and a name: \(name)")
})
这将为检索到的每个孩子打印一个用户和一个名字
This will print a user and a name for every child that is retrieved
这篇关于当Firebase功能在Swift中结束时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!