使用 Swift 在 Firebase 中完成异步任务 [英] Finish asynchronous task in Firebase with Swift
本文介绍了使用 Swift 在 Firebase 中完成异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数,该函数将返回我所有工人的数组,但它在从 firebase 检索数据之前返回
这是我的代码:
func getWorkersList() -> ([Worker])
{
let workersInfoRef = ref.childByAppendingPath("countries/(userCountry)/cities/(userCity)/workers/(workFieldToRecieve)/")
var workerList = [Worker]()
workersInfoRef.queryOrderedByChild("name").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
print(snapshot.childrenCount)
for rest in snapshot.children.allObjects as! [FDataSnapshot]{
let workerInfo = Worker(uid: rest.value["uid"] as! String, name: rest.value["name"] as! String, city: rest.value["city"] as! String, profession: rest.value["profession"] as! String, phone: rest.value["phone"] as! String, email: rest.value["email"] as! String, country: rest.value["country"] as! String)
workerList.append(workerInfo)
}
}) { (error) in
print(error.description)
}
print(workerList.count)
return workerList
}
推荐答案
这没有经过测试...我只是在运行中编写了代码以提供总体思路
为您的函数添加一个完成块/回调...
add a completion block/callback to your function...
func getWorkersList(callback: ((data:[Worker]) ->Void )) {
let workersInfoRef = ref.childByAppendingPath("countries/(userCountry)/cities/(userCity)/workers/(workFieldToRecieve)/")
var workerList = [Worker]()
workersInfoRef.queryOrderedByChild("name")
.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
print(snapshot.childrenCount)
for rest in snapshot.children.allObjects as! [FDataSnapshot]{
let workerInfo = Worker(uid: rest.value["uid"] as! String, name: rest.value["name"] as! String, city: rest.value["city"] as! String, profession: rest.value["profession"] as! String, phone: rest.value["phone"] as! String, email: rest.value["email"] as! String, country: rest.value["country"] as! String)
workerList.append(workerInfo)
}
print(workerList.count)
callback(workerList)
}) { (error) in print(error.description) }
}
传入完成块..
getWorkersList(callback: { (data:[Worker]) -> Void in
print(data)
})
这篇关于使用 Swift 在 Firebase 中完成异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文