【发布时间】:2017-08-17 16:03:02
【问题描述】:
我正在尝试在 for 循环中从 firebase 获取一些数据,但它不起作用。
我知道我应该使用 DispatchQueue,但我不明白我应该如何将它与 Firebase 一起使用。
我有一个循环:
for i in 0..<Exercice.workout.count{
exercice = (Exercice.workout[i] as! [[Any]])[0][0] as! String
print("Exercice: \(exercice)")
self.endDeleteLastSerie(key: key, exercice: exercice, callback: {(status, endTime) in
if status == "success"{
print("do stuff here")
let index = self.getIndexOfExercice(exerciceName: exercice)
print("Index: \(index)")
print("ExerciceName: \(exercice)")
}
}
在我的函数 endDeleteLastSerie 中,我正在调用 2 个 firebase 函数
func endDeleteLastSerie(key:String, exercice: String, callback: @escaping(_ status:String, _ endTime: Int)->Void){
FirebaseWorkout.deleteSerie(key: key, exercice: exercice) { (status) in
if status == "success" {
//we set the end time to firebase
FirebaseWorkout.updateEndExercice(exercice: exercice, callback: { (status, endTime) in
if status == "success" {
callback("success", endTime)
}else{
callback("error", endTime)
}
})
}
}
}
**** 我的 Firebase 功能之一的示例 ****
static func deleteSerie(key: String, exercice: String, callback: @escaping (_ status: String)->Void){
let uid = FirebaseUsers.User.uid
print("remove")
Database.database().reference().child("users/"+uid+"/workout/"+self.workoutKey+"/exercice/"+exercice+"/series/"+key).removeValue { (error, DatabaseReference) in
if error == nil {
print("removed from firebase")
callback("success")
}else{
callback("error")
}
}
}
但我得到的是:
Exercice: Bench Press
remove
Exercice: Pectoral Fly
remove
removed from firebase
removed from firebase
do stuff here
Index: 1
ExerciceName: Pectoral Fly
do stuff here
Index: 1
ExerciceName: Pectoral Fly
我尝试在里面添加我的 for 循环:
DispatchQueue.main.sync { }
或
DispatchQueue.global().sync(execute: { })
或
var _dispatchQueue:DispatchQueue = DispatchQueue(label: "first", qos: .userInteractive)
然后在里面添加我的for循环
self._dispatchQueue.sync { }
但没有任何效果
我该如何解决这个问题?并得到
Exercice: Bench Press
remove
removed from firebase
do stuff here
Index: 0
ExerciceName: Bench Press
Exercice: Pectoral Fly
remove
removed from firebase
do stuff here
Index: 1
ExerciceName: Pectoral Fly
【问题讨论】:
-
你想通过在这里使用
DispatchQueue来完成什么? Firebase SDK 已经在主线程之外完成了所有的网络交互。它在主线程上所做的只是调用你的回调/完成处理程序。 -
问题是,在从 firebase 获得回调后,我从我的 for 循环中获得了价值。当我得到firebase的回调时,我会...... let index = self.getIndexOfExercice(exerciceName: exercice) 但我总是得到“Pectoral Fly”作为 exerciceName
-
我在回调中添加了 2 个 print 以便您更好地理解我得到的内容。我添加了控制台日志中显示的打印内容。 @Frank van Puffelen
标签: swift firebase firebase-realtime-database grand-central-dispatch