gpt4 book ai didi

swift - 使用 Swift 在 Firebase 中完成异步任务

转载 作者:行者123 更新时间:2023-11-28 11:06:48 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来返回我所有工作人员的数组,但它在从 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

}

最佳答案

这没有经过测试...我只是即时编写代码来给你一个大概的想法

向您的函数添加一个完成 block /回调...

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

传入完成 block ..

getWorkersList(callback: { (data:[Worker]) -> Void in 
print(data)
})

关于swift - 使用 Swift 在 Firebase 中完成异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com